问题
How can I group by relation?
Example
Sales::with('product_detail.product')->groupBy('product_name')->get()
How can I get a result with eloquent code?
回答1:
You can specify a callback function for grouping your relation like this:
Sales::with(['product_detail.product' => function($query){
$query->groupBy('product_name');
}])->get();
回答2:
this will help you to do grouping by relation.
$sales = Order::Sales('product')
->where('approved','=','Yes')
->groupBy('product_id')
->orderBy(DB::raw('COUNT(id)','desc'))
->get(array(DB::raw('COUNT(id) as totalsales'),'product_id'));
来源:https://stackoverflow.com/questions/36468759/laravel-grouping-by-eloquent-relationship