Reputation: 21
I need to have an order (table order) that has "hasMany" relation to item. I need to only get the order that has a certain date on one of its item and only the concerned items.
For example, if I have an order : Order 1 that has 2 items, one that is created the first january and the other in december and I search with the first january, i want to get the order and the item.
$order = Order::with('items')->whereHas(
'items', function ($query) use ($dateFrom, $dateTo) {
return $query->whereBetween('date_debut', [$dateFrom->format('Y-m-d').' 00:00:00', $dateTo->format('Y-m-d').' 00:00:00'])
->with([
'titles.title',
]);
})->get();
With that code, I always get all the items of the order and not only the one I want
Upvotes: 0
Views: 47
Reputation: 12188
with inside whereHas has no effects.
you should apply your condition on the eager load relation itself:
$orders = Order::with(['items'=>function($query) use ($dateFrom, $dateTo){
return $query->whereBetween('date_debut', [$dateFrom->format('Y-m-d').' 00:00:00', $dateTo->format('Y-m-d').' 00:00:00'])
->with(['titles.title']);
}])->whereHas(
'items', function ($query) use ($dateFrom, $dateTo) {
$query->whereBetween('date_debut', [$dateFrom->format('Y-m-d').' 00:00:00', $dateTo->format('Y-m-d').' 00:00:00']);
})->get();
note if you want all the orders regardless if they has items wherebetween
, you can remove the whereHas
statements.
Upvotes: 1