Laravel 集合 group by

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45359514/
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-14 16:23:30  来源:igfitidea点击:

Laravel collection group by

phplaravel

提问by Hardist

I have a search function to search for expenses by a certain date, month, string, whatever. It returns a collection:

我有一个搜索功能,可以按特定日期、月份、字符串等搜索费用。它返回一个集合:

enter image description here

在此处输入图片说明

So far so good. I can display all returned Expenses. Now, what I want to do is, display also a total expense count and total amount, grouped by the description_id. If I simply do $result->groupBy('description_id), I just get a set of collections, from which I can display the total count and total amount, but not the name of the description. Example of what I want:

到现在为止还挺好。我可以显示所有返回的Expenses. 现在,我想要做的是,还显示总费用计数和总金额,按description_id. 如果我只是这样做$result->groupBy('description_id),我只会得到一组集合,从中我可以显示总计数和总金额,但不能显示描述的名称。我想要的例子:

Grouped Results (By Expense):

Description Name: <-- Issue displaying this
Total Expenses: 3
Total Amount: 53444

The description name can only be obtained via the relation between Expenseand Description. An Expense belongsTo a description.

描述名只能经由之间的关系来获得ExpenseDescription。费用属于描述。

Is it at all possible to achieve what I want, when working with my collection, or should I perform a seperate query for those results? (undesired)

在处理我的收藏时,是否有可能实现我想要的结果,或者我应该对这些结果执行单独的查询?(不想要的)

回答by Oluwatobi Samuel Omisakin

If you eager-load description, then you can group the resulting collection by the nested object of the collection. So you may have:

如果您预先加载description,那么您可以通过集合的嵌套对象对结果集合进行分组。所以你可能有:

$expenses = Expenses::with('description')->get(); //collection

Then group it:

然后分组:

$grouped = $expenses->groupBy('description.name'); 
//or
$grouped = $expenses->groupBy('description_id'); 

Then you can use the name of description, accessing it, say we need the first group, and the first expense in the group,

然后你可以使用description的名字,访问它,说我们需要第一组,以及组中的第一笔费用,

$description_name = $grouped
                    ->first() //the first group
                    ->first() //the first expense in group
                    ->description //the description object
                    ->name //the name

This is just a little proof that you can get the name of the related model in the collection and use it to solve your question.

这只是一个小证明,您可以在集合中获取相关模型的名称并使用它来解决您的问题。