This might be quite easy but have no idea how to.
I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query using Query Builder or Eloquent that will fetch rows with distinct values for that column?
Note that I am not fetching that column only, it is in conjunction with other column values, so distinct()
might not really work. So that question basically can be how to specify the column that I want to be distinct in a query now that distinct()
accepts no parameters?
You should use groupby
. In Query Builder you can do it this way:
$users = DB::table('users')
->select('id','name', 'email')
->groupBy('name')
->get();
In Eloquent you can also query like this:
$users = User::select('name')->distinct()->get();
in eloquent you can use this
$users = User::select('name')->groupBy('name')->get()->toArray() ;
groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values
Though I am late to answer this, a better approach to get distinct records using Eloquent would be
$user_names = User::distinct()->get(['name']);
Note that groupBy
as used above won't work for postgres.
Using distinct
is probably a better option - e.g.
$users = User::query()->distinct()->get();
If you use query
you can select all the columns as requested.
Grouping by will not work if the database rules don't allow any of the select fields to be outside of an aggregate function. Instead use the laravel collections.
$users = DB::table('users')
->select('id','name', 'email')
->get();
foreach($users->unique('name') as $user){
//....
}
$users = User::select('column1', 'column2', 'column3')->distinct()->get();
retrieves all three coulmns for distinct rows in the table. You can add as many columns as you wish.
$users = Users::all()->unique('name');
来源:https://stackoverflow.com/questions/25228823/how-to-get-distinct-values-for-non-key-column-fields-in-laravel