How to get distinct values for non-key column fields in Laravel?

帅比萌擦擦* 提交于 2019-11-28 07:54:39

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.

Roland Verner
$users = Users::all()->unique('name');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!