Group_concat - laravel eloquent

半世苍凉 提交于 2020-01-09 11:18:06

问题


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:

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

Thanks in advance :)


回答1:


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




回答2:


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, []);



回答3:


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



回答4:


or just replace

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

with

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



回答5:


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.




回答6:


$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();


来源:https://stackoverflow.com/questions/25847738/group-concat-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!