Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use GROUP_CONCAT in laravel

$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

like image 487
Dipankar Naskar Avatar asked Nov 08 '16 11:11

Dipankar Naskar


People also ask

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.

What does Group_concat do in SQL?

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.


4 Answers

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();
like image 82
Amit Gupta Avatar answered Oct 04 '22 17:10

Amit Gupta


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();
like image 37
shoieb0101 Avatar answered Oct 04 '22 18:10

shoieb0101


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.

like image 37
Saumya Rastogi Avatar answered Oct 04 '22 18:10

Saumya Rastogi


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));
like image 32
Nazmul Hasan Avatar answered Oct 04 '22 17:10

Nazmul Hasan