Laravel 按 Eloquent 关系分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36468759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:19:09  来源:igfitidea点击:

Laravel Grouping by Eloquent Relationship

laravelrelation

提问by yudijohn

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?

如何使用雄辩的代码获得结果?

回答by Imtiaz Pabel

You can specify a callback function for grouping your relation like this:

您可以指定一个回调函数来对您的关系进行分组,如下所示:

Sales::with(['product_detail.product' => function($query){
        $query->groupBy('product_name');
    }])->get();

回答by Sahil Dawka

I think the top answer is not answering the question. As I understand, the aim is to group the results of the outer query, not the relationship.

我认为最重要的答案不是回答问题。据我了解,目的是对外部查询的结果进行分组,而不是对关系进行分组。

This is not possible in an Eloquent-y DB call because the call for the With is separate. You can manually join the tables and group by the required column.

这在 Eloquent-y DB 调用中是不可能的,因为对 With 的调用是分开的。您可以手动加入表并按所需列分组。

If you want to stay Eloquent-y, there are many convenient methods available to Collections, including GroupBy. So you can get the data first and group later.

如果你想保持 Eloquent-y,Collections 有很多方便的方法,包括 GroupBy。所以你可以先获取数据,然后再分组。

回答by Shrikant Bhardwaj

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'));