How to use GROUP_CONCAT in laravel

$assignment = assignment::find(Crypt::decrypt($id)); $assignment_details = $assignment->raw_plan()->groupBy('flag')->get(); 

I want to get the 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 to use GROUP_CONCAT in laravel

+6
source share
4 answers

You can use relationships as a query builder to get results like:

 $assignment_details = $assignment->raw_plan() ->select(DB::raw('group_concat(name) as names')) ->where('assignment_id', 1) ->groupBy('flag') ->get(); 

Update

Use table_name.* To select all fields.

 $assignment_details = $assignment->raw_plan() ->select('raw_plans.*', DB::raw('group_concat(name) as names')) ->where('assignment_id', 1) ->groupBy('flag') ->get(); 
+12
source

shoieb is somewhat correct, but you must specify the table name before accessing the column names in DB:raw()

You should try the following:

 $data = DB::table('raw_plans') ->select(DB::raw("group_concat(raw_plans.name)")) ->groupBy('flag') ->where('assignement_id',1) ->get(); 

Hope this helps.

+5
source

Try using the code below

 $data = DB::table('raw_plans') ->select(DB::raw("GROUP_CONCAT(name SEPARATOR '-') as `names`")) ->groupBy('flag') ->where('assignement_id',1) ->get(); 
+2
source

try it

 $sql = "SELECT GROUP_CONCAT(name) AS 'names' FROM `raw_plans` where `assignment_id` = 1 GROUP BY`flag`"; $info = DB::select(DB::raw($sql)); 
0
source

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


All Articles