本文介绍了如何在雄辩的ORM中使用groupBy()对集合进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是检索用户的所有项目",然后按其状态"分组显示在我的视图中.有4种可能的状态,每个状态在包含项目信息的页面上都有自己的< div> .经过一番摸索后,我相信我需要像这样使用 groupBy()方法:

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. After some poking around I believe I need to use the groupBy() method like so:

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

这似乎确实做了某种分组,但是当我遍历集合时,我最多得到4个结果,每个状态一个.这并不能真正解决我的问题,因为我需要针对每个状态显示用户的所有项目,而不仅仅是一个.我必须在这里丢失一些东西,我真的想避免对每种状态进行查询并以这种方式显示它们.我想我可以按状态过滤集合并创建4个新集合,但这不是 groupBy()应该做的吗?

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. 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?

推荐答案

使用laravel和Collections可以很容易地做到这一点.集合具有强大的API和许多方便的方法,可以轻松实现所需的目标.

You can do that very easy with laravel and Collections. Collections have powerful API and a lot of handy methods, to easily achieve what you want.

您在这里的错误是,您正在对QueryBuilder对象调用groupBy,该对象仅返回按数据库记录分组的对象.相反,您必须选择所需的所有记录,然后它们将作为集合返回.之后,您可以根据需要操纵集合.因此,您需要的是:

Your mistake here is that you are calling groupBy on the QueryBuilder object which returns only groupped by records from the database. 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');

您可以在此处查看所有Colletion类有用的方法.

You can view all of the Colletion class useful methods here.

这篇关于如何在雄辩的ORM中使用groupBy()对集合进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:30