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

前端 未结 14 1389
太阳男子
太阳男子 2020-12-01 09:09

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 usin

相关标签:
14条回答
  • 2020-12-01 09:09

    $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.

    0 讨论(0)
  • 2020-12-01 09:10

    You should use groupby. In Query Builder you can do it this way:

    $users = DB::table('users')
                ->select('id','name', 'email')
                ->groupBy('name')
                ->get();
    
    0 讨论(0)
  • 2020-12-01 09:11

    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

    0 讨论(0)
  • 2020-12-01 09:11

    I found this method working quite well (for me) to produce a flat array of unique values:

    $uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
    

    If you ran ->toSql() on this query builder, you will see it generates a query like this:

    select distinct `name` from `users`
    

    The ->pluck() is handled by illuminate\collection lib (not via sql query).

    0 讨论(0)
  • 2020-12-01 09:15

    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.

    0 讨论(0)
  • 2020-12-01 09:21
    $users = Users::all()->unique('name');
    
    0 讨论(0)
提交回复
热议问题