10

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 :)

user3481058
  • 313
  • 2
  • 4
  • 18
  • Try using DB::raw() to wrap 'raw' SQL you want in a query: `->select('commands.username',DB::raw('group_concat(products.name)'))` – alexrussell Sep 15 '14 at 12:17
  • thanks for your reply @alexrussell but the problem is that when I add the DB::raw and I run again the application I get this error: Symfony \ Component \ Debug \ Exception \ FatalErrorException Class 'Storage\Commands\DB' not found – user3481058 Sep 15 '14 at 12:38
  • Ahh you're in a namespace - either add `use DB;` after your namespace declaration or use `DB` in your code: `\DB::raw('group_concat(products.name)')` – alexrussell Sep 15 '14 at 13:13

6 Answers6

12

I just used:

use DB;

and in my query I used

DB::raw('group_concat(products.name)')

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
user3481058
  • 313
  • 2
  • 4
  • 18
6

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
Uttam Panara
  • 541
  • 2
  • 10
  • 28
6

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, []);
Sharath
  • 2,348
  • 8
  • 45
  • 81
2

or just replace

->select('commands.username','**group_concat(products.name)**')

with

->selectRaw('commands.username, **group_concat(products.name)**')
cabs
  • 710
  • 7
  • 14
0

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.

Nisar P
  • 316
  • 2
  • 9
-3

$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();