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

前端 未结 14 1680
太阳男子
太阳男子 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:32

    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){
      //....
    }
    

    Someone pointed out that this may not be great on performance for large collections. I would recommend adding a key to the collection. The method to use is called keyBy. This is the simple method.

         $users = DB::table('users')
            ->select('id','name', 'email')
            ->get()
            ->keyBy('name');
    

    The keyBy also allows you to add a call back function for more complex things...

         $users = DB::table('users')
            ->select('id','name', 'email')
            ->get()
            ->keyBy(function($user){
                  return $user->name . '-' . $user->id;
             });
    

    If you have to iterate over large collections, adding a key to it solve the performance issue.

提交回复
热议问题