Laravel collection group by

倾然丶 夕夏残阳落幕 提交于 2021-01-18 10:40:22

问题


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

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:

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 Expense and Description. An Expense belongsTo a description.

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)


回答1:


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

$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_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.



来源:https://stackoverflow.com/questions/45359514/laravel-collection-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!