Laravel 按多列分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39660693/
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
laravel grouping by multiple columns
提问by Suemayah Eldursi
Im using laravel 5.2 and I want to group a table based on the value of two columns (configuration and type). So basically if two or more rows in the table have the same configuration and type they will be grouped. I've tried querying like this and its not working:
我使用 laravel 5.2,我想根据两列(配置和类型)的值对表进行分组。所以基本上如果表中的两行或更多行具有相同的配置和类型,它们将被分组。我试过这样查询,但它不起作用:
$groups = Model::where('active', 1)->get()->groupBy('type_id', 'configuration_id');
Any suggestions?
有什么建议?
EDIT: I think I'm using the wrong query. What I want to do is get the rows that have the same values in these two columns and have them grouped. Apparently group by is used to aggregate things e.g if I want a sum or something.
编辑:我想我使用了错误的查询。我想要做的是获取在这两列中具有相同值的行并将它们分组。显然 group by 用于聚合事物,例如,如果我想要一个总和或其他东西。
EDIT 2: Actually the groupby here I'm using is not part of the query it is a helper function provided by laravel to use on collections see this linkDoes anyone know if it groups by two feilds??
编辑 2:实际上,我在这里使用的 groupby 不是查询的一部分,它是 laravel 提供的用于集合的辅助函数,请参阅此链接有谁知道它是否按两个字段分组?
回答by Ali Abbas
Pass Columns names in array form this is working for me
以数组形式传递列名称这对我有用
$groups = Model::where('active', 1)->groupBy(['type_id', 'configuration_id','etc']);
回答by Komal
Try like this
像这样尝试
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id');
回答by Suemayah Eldursi
Ok I've figured it out. The groupBy method I'm using is not a query it is a laravel function that groups collections by a certain feild. You can see the documentation here. So the workaround was to do the grouping twice like this.
好的,我想通了。我使用的 groupBy 方法不是查询,它是一个按特定领域对集合进行分组的 laravel 函数。您可以在此处查看文档。所以解决方法是像这样进行两次分组。
$groups = Model::where('active', 1)->get()->groupBy('type_id');
foreach ($groups as $group) {
$grouped[] = $group->groupBy('configuration_id');
}
If anyone has a more efficient way of doing this I would like to see their way of doing it.
如果有人有更有效的方法来做到这一点,我希望看到他们的做法。
回答by Dmytrechko
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get();
回答by Rama Durai
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get(['type_id', 'configuration_id']);