babu.desai@icloud.com's avatar

get unique rows

i have table called machines that has category column. in view im trying to make dropdown select of categories. and since there are many machines with same category, when i make select lift i get duplicate categories to choose from. how can i get categories only once

0 likes
8 replies
andonovn's avatar

Use the following database query: select category from machines group by category or select distinct category from machines

If you are using the default Laravel setup (ie with Eloquent), that may look like \App\Machine::groupBy('category')->get();

Without Eloquent it should be \DB::table('machines')->groupBy('category')->get();

Snapey's avatar

$categories = DB::table('machines')->distinct('category')->pluck('category');

1 like
babu.desai@icloud.com's avatar

adonovn, that didn't work i got error Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'machinerytradeoff.machines.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from machines group by category)

Snapey's avatar
Snapey
Best Answer
Level 122

Yes of course;

$categories = Machine::distinct('category')->pluck('category');


10 likes
Snapey's avatar

mark it as solved if you are happy, please.

1 like
andonovn's avatar

@babu.desai@icloud.com the error is because the query I gave will select all the columns but grouping by only one and that's incompatible with sql_mode=only_full_group_by.

Basically, in that mode, MySQL is not letting you select columns that may have arbitrary values. In your case let's say you have another column called random which has value asd in row 1 and value dsa in row 2. But imagine both row 1 and row 2 has the same category of some-category-name. Now when you group by some-category-name MySQL won't know if you need the asd or dsa for your random column. Hope that makes sense :)

The solution is to select just the category column which using Eloquent should look like \App\Machine::groupBy('category')->pluck('category');

Please or to participate in this conversation.