Group_concat - laravel eloquent

please, I want to use group_concat in the request, using eloquent rather than raw requests.

here is the code that I tried to execute and did not work for me:

commands::join('products', 'products.id', '=','commands.idproduct') ->select('commands.username','**group_concat(products.name)**') ->group by ('commands. username') ->get(); 

Thanks in advance:)

+5
source share
6 answers

I just used a DB; and in my query I used DB :: raw ('group_concat (products.name)') !!

+10
source

It 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, []); 
+4
source

The best example for him.

 
 ModelName :: select ('ID', DB :: raw ('CONCAT (First_Name, "", Last_Name) AS full_name'))
            -> get ()
            -> toArray ();

 Result 
    Jon Doe, Jeffery Way, Tailer, taylor otwell
+3
source

or just replace

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

from

 ->selectRaw('commands.username, **group_concat(products.name)**') 
+2
source

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
source

$ 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 (description of DISTINCT) as description') -> where ('paging_config.page_group', '=', 'paging_config.page_group') -> group ('paging_config.description')

  ->get(); 
-3
source

Source: https://habr.com/ru/post/1202588/


All Articles