Reputation: 2183
I have table with attributes. Table has columns: attr_id
, value
.
I want group records by attr_id
and prevent duplicates, because in table can be multiple attr_id
with: 3,2,1 ids. I need to show list of this attributes grouped by attr_id.
How can I do this?
$attrs = Attribute::groupBy('attr_id')->get();
not working.
Error:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.attributes.value' which is not functionally dependent on columns
Upvotes: 1
Views: 2220
Reputation: 3277
I think what you are looking for is:
$attrs = Attribute::get()->groupBy('attr_id');
That will use groupBy() function from Laravel collections https://laravel.com/docs/5.6/collections#method-groupby
Else you are using "group by" incorrectly because you have to specify all the keys you want to be returned. You should read what group by does: https://www.w3schools.com/sql/sql_groupby.asp https://www.tutorialspoint.com/sql/sql-group-by.htm
Upvotes: 1