Laravel 和 PHP 的新手,所以遇到一個小問題很難:
我正在深入到一個集合中,并希望只帶回滿足特定(可選)日期條件的嵌套專案。
不幸的是,它不起作用(根本不起作用)。這是我的代碼:
public function getAnalyticsData(Request $request): JsonResponse
{
$data = collect();
$user = $request->user();
// Incoming request params
$dataType = $request->input('data-type');
$startDate = $request->filled('start-date') ? strtotime($request->input('start-date')) : '';
$endDate = $request->filled('end-date') ? strtotime($request->input('end-date')) : '';
if ($dataType === 'orders') {
$workgroupId = $request->input('workgroup-id');
$workgroups = Workgroup::where('id', $workgroupId)->with('analyticsOrders')->get();
$ordersData = $workgroups->map(function ($order) use ($startDate, $endDate) {
return collect($order)->only(['analytics_orders'])->map(function ($item) use ($startDate, $endDate) {
return collect($item)->when($startDate, function ($query) use ($startDate) {
$query->where('created_at', '>=', $startDate);
})->when($endDate, function ($query) use ($endDate) {
$query->where('created_at', '<=', $endDate);
});
});
});
$data->put('analyticsData', $ordersData);
} else if ($dataType === 'integrations') {
$data->put('analyticsData', $user);
}
// This is just to return something, please ignore
return response()->jsonSuccess($data);
}
雖然我引起了您的注意,但我如何才能只回傳analytics_orders如下所示的陣列(現在資料非常混亂):

uj5u.com熱心網友回復:
我猜你已經混合了laravel collection和eloquent collection。Eloquent 集合位于 Laravel 集合之上,反之亦然。
在laravel集合中,當你使用when()method時,一個那個集合會被傳遞給閉包函式,laravel eloquent和$queryobject沒有任何東西。你有那個集合實體,你應該在你的閉包函式中回傳一些東西。
因此,如下編輯您的閉包函式并使用return
return collect($item)->when($startDate, function ($collection) use ($startDate) {
return $collection->where('created_at', '>=', $startDate);
})->when($endDate, function ($collection) use ($endDate) {
return $collection->where('created_at', '<=', $endDate);
});
uj5u.com熱心網友回復:
查看集合的pluck方法。它將允許您從集合中選擇您想要的鍵。在這種情況下,您可能需要這樣的一行。
$data->put('analyticsData', $ordersData->pluck('id','created_at'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344484.html
上一篇:未定義的屬性:Illuminate\Pagination\LengthAwarePaginator::$category
