问题
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