Reputation: 346
$assignment = assignment::find(Crypt::decrypt($id));
$assignment_details = $assignment->raw_plan()->groupBy('flag')->get();
I want to following result of this query in laravel
SELECT GROUP_CONCAT(name) AS 'names' FROM `raw_plans` where `assignment_id` = 1 GROUP BY`flag`
Please suggest me how to use GROUP_CONCAT in laravel
Upvotes: 23
Views: 55083
Reputation: 17658
You can use relations as query builder to fetch the results as:
$assignment_details = $assignment->raw_plan()
->select(DB::raw('group_concat(name) as names'))
->where('assignment_id', 1)
->groupBy('flag')
->get();
Update
Use table_name.*
in select to get all the fields.
$assignment_details = $assignment->raw_plan()
->select('raw_plans.*', DB::raw('group_concat(name) as names'))
->where('assignment_id', 1)
->groupBy('flag')
->get();
Upvotes: 35
Reputation: 13693
shoieb is somewhat right, but you should give table name before accessing column names in DB:raw()
You should try this:
$data = DB::table('raw_plans')
->select(DB::raw("group_concat(raw_plans.name)"))
->groupBy('flag')
->where('assignement_id',1)
->get();
Hope this helps.
Upvotes: 8
Reputation: 1977
Try this
$sql = "SELECT GROUP_CONCAT(name) AS 'names' FROM `raw_plans` where `assignment_id` = 1 GROUP BY`flag`";
$info = DB::select(DB::raw($sql));
Upvotes: 2
Reputation: 1582
Try with below code
$data = DB::table('raw_plans')
->select(DB::raw("GROUP_CONCAT(name SEPARATOR '-') as `names`"))
->groupBy('flag')
->where('assignement_id',1)
->get();
Upvotes: 12