Group_concat - laravel eloquent

后端 未结 6 2035
我在风中等你
我在风中等你 2020-12-06 18:29

please I want to use group_concat in a query using eloquent and not raw queries.

here is the code which i tried to execute and did\'t work for me:

co         


        
相关标签:
6条回答
  • 2020-12-06 19:09

    This worked for me

    $list = TableName::where('user_id', 'user_001'
            ->groupBy('user_id')
            ->groupBy('subscription_id')
            ->select('user_id','subscription_id','type')
            ->selectRaw('GROUP_CONCAT(holiday) as holidays')
            ->get();
    

    or

    use Illuminate\Support\Facades\DB;
    
    $sql = 'SELECT GROUP_CONCAT(holiday) as holidays, user_id,subscription_id, type FROM TableName 
            where vendor_id = 'user_001' GROUP BY user_id, subscription_id;';
    $list = DB::select($sql, []);
    
    0 讨论(0)
  • 2020-12-06 19:21

    Best example for it..

     
    ModelName::select('ID', DB::raw('CONCAT(First_Name, " ", Last_Name) AS full_name'))
               ->get()
               ->toArray();
    
    Result 
       Jon Doe,Jeffery Way,Tailer,taylor otwell
    
    0 讨论(0)
  • 2020-12-06 19:32

    $data=\DB::table('paging_config') ->leftjoin('paging_groups', 'paging_config.page_group', '=', 'paging_groups.page_number') ->leftjoin('spk_mnt', 'paging_groups.ext', '=', 'spk_mnt.stn_no') ->select('paging_config.page_group','paging_groups.ext', 'spk_mnt.stn_status') ->selectRaw('GROUP_CONCAT(DISTINCT description) as description') ->where('paging_config.page_group','=','paging_config.page_group') ->groupBy('paging_config.description')

            ->get();
    
    0 讨论(0)
  • I just used:

    use DB;

    and in my query I used

    DB::raw('group_concat(products.name)')

    0 讨论(0)
  • 2020-12-06 19:34

    This worked for me: (9.0+)

    DB::raw('string_agg(products.name, \',\') as products')
    

    You will need to use Illuminate\Support\Facades\DB; for this.

    0 讨论(0)
  • 2020-12-06 19:35

    or just replace

    ->select('commands.username','**group_concat(products.name)**')
    

    with

    ->selectRaw('commands.username, **group_concat(products.name)**')
    
    0 讨论(0)
提交回复
热议问题