$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
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(); Use table_name. * in select to get all the fields.
The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.
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();
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();
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With