I've been stuck a few days trying to get something that I think should be really simple but I'm not able to find the right solution,
I have the following Models (just printing the important methods)
Order
id
created_at
OrderContent
id
order_id
I have a scope in Order
scopeByRange($query,$d1,$d2){
return $query->whereBetween('created_at',[$d1,$d2])
}
Which works perfectly, what I want to get is a collection with all the orderContents from that OrderScope
Something like
$orderContents = Order::byRange($d1,$d2)->allOrderContents;
So I don't have to do a bucle and merge the collections
Is there a way?
Thanks to @JarekTkaczky for pointing me to the right direction, my final function is the following one, is just do some extra calculations for reports
public static function byDateRange($d1,$d2){
$orderContents = null;
Order::byDateRange($d1,$d2)->with(['contents' => function($q) use(&$orderContents){
$orderContents = $q->select('*',
DB::raw('sum(quantity) as quantity_sum'),
DB::raw('sum(total) as total_sum'))
->groupBy('item_id')
->orderBy('total_sum','DESC')
->get()->unique();
},'contents.item'])->get();
return $orderContents;
}