laravel 按 Eloquent ORM 分组

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

Group By Eloquent ORM

laravelgroup-bylaravel-4eloquent

提问by Hugo Gresse

I was searching for making a GROUP BY nameEloquent ORM docsbut I haven't find anything, neither on google.

我正在寻找制作GROUP BY nameEloquent ORM 文档,但我没有找到任何东西,在谷歌上也没有。

Does anyone know if it's possible ? or should I use query builder ?

有谁知道这是否可能?还是应该使用查询构建器?

回答by Antonio Carlos Ribeiro

Eloquent uses the query builder internally, so you can do:

Eloquent 在内部使用查询构建器,因此您可以执行以下操作:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

回答by chebaby

Laravel 5

Laravel 5

This is working for me (i use laravel 5.6).

这对我有用(我使用laravel 5.6)。

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

如果要将集合转换为普通的 php 数组,可以使用toArray()

$array = MyModel::all()->groupBy('column')->toArray();