简体   繁体   English

如何在雄辩的ORM中使用groupBy()对集合进行分组

[英]How to use groupBy() in Eloquent ORM to group a collection

My goal is to retrieve all of a user's 'items' and display then in my view grouped by their 'status'. 我的目标是检索用户的所有“项目”,然后按其“状态”分组显示在我的视图中。 There are 4 possible statuses, each with their own <div> on the page containing the items' info. 有4种可能的状态,每个状态在包含项目信息的页面上都有自己的<div> After some poking around I believe I need to use the groupBy() method like so: 经过一番groupBy() ,我相信我需要像这样使用groupBy()方法:

$items = Item::ownedBy( Auth::id() )->groupBy('status')->get();

This does seem to do some sort of grouping, but when I iterate over the collection I get a max of 4 results, one for each status. 这似乎确实做了某种分组,但是当我遍历集合时,我最多得到4个结果,每个状态一个。 This doesn't really solve my problem as I need to display all of a user's items for each status, not just one. 这并不能真正解决我的问题,因为我需要针对每个状态显示用户的所有项目,而不仅仅是一个。 I must be missing something here, I'd really like to avoid making a query for each status and displaying them that way. 我必须在这里丢失一些东西,我真的很想避免对每种状态进行查询并以这种方式显示它们。 I suppose I could filter the collection by status and create 4 new collections, but isn't this what groupBy() is supposed to do? 我想我可以按状态过滤集合并创建4个新集合,但这不是groupBy()应该做的吗?

You can do that very easy with laravel and Collections. 您可以使用laravel和Collections非常轻松地做到这一点。 Collections have powerful API and a lot of handy methods, to easily achieve what you want. 集合具有强大的API和许多方便的方法,可以轻松实现所需的功能。

Your mistake here is that you are calling groupBy on the QueryBuilder object which returns only groupped by records from the database. 您在这里的错误是,您正在对QueryBuilder对象调用groupBy,该对象仅返回按数据库记录分组的对象。 Instead you must select all of the records you need, then they will be returned as a collection. 相反,您必须选择所需的所有记录,然后它们将作为集合返回。 After that you can manipulate the collection as you wish. 之后,您可以根据需要操纵集合。 So what you need is: 因此,您需要的是:

$items = Item::ownedBy( Auth::id() )->get()->groupBy('status');

You can view all of the Colletion class useful methods here . 您可以在此处查看所有Colletion类有用的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM