Laravel 5.5 Eloquent 在多于 1 列的情况下变得不同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46422496/
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 5.5 Eloquent get distinct with more than 1 column
提问by Jim
I have a table which is indexed by id and also has a column description.
我有一个由 id 索引的表,还有一个列描述。
I want to use this in a form with it populating a radio group.
我想以填充无线电组的形式使用它。
My problem is if I try
我的问题是如果我尝试
$colours = Colours::where('manufacturer_id',"=",$man)->select('id','description')->orderBy('description')->groupBy('description')->get();
I get
我得到
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cl24-ids.colours.manufacturer_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select
description
,manufacturer_id
fromcolours
wheremanufacturer_id
= 1 group bydescription
)
SQLSTATE[42000]:语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 子句中,并且包含非聚合列“cl24-ids.colours.manufacturer_id”,它在功能上不依赖于 GROUP BY 子句中的列;这与 sql_mode=only_full_group_by (SQL: select
description
,manufacturer_id
fromcolours
wheremanufacturer_id
= 1 group bydescription
)不兼容
Any ideas please or should I just use a non Eloquent solution?
请问有什么想法还是我应该只使用非 Eloquent 解决方案?
回答by Pawan Kumar
The distinct method allows you to force the query to return distinct results:
distinct 方法允许您强制查询返回不同的结果:
$users = DB::table('users')->distinct()->get();
Get unique rows
获取唯一行
$categories = Machine::distinct('category')->pluck('category','antoher');
回答by Mr. Pyramid
$colours = Colours::where('manufacturer_id',"=",$man)
->select('id','description')->groupBy('description')->get();
回答by Ajay
You can get distinct data just pass column as array in get method with distinct.
您可以获取不同的数据,只需在 get 方法中将列作为数组传递给 distinct 即可。
$myusers = User::distinct()->get(['created_by']);
$myusers = User::distinct()->get(['created_by']);