Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel selectRaw with joined table data

I am using the following to sum a total column:

$hive_count = Hive::where('active','true')
                      ->groupBy('hive_type_id')
                      ->selectRaw('sum(total) as sum, hive_type_id')
                      ->pluck('sum','hive_type_id');

But rather than using the hive_type_id for the array key, I would like to access the hive_type name from the hive_types table (column 'name'). I have tried hive_type_id.name but this did not work.

Models: Hive & HiveType

Thanks for your help.

like image 785
Pedro Avatar asked Dec 04 '16 22:12

Pedro


1 Answers

I would like to access the hive_type name from the hive_types table (column 'name').

You've to join the table hive_types in your query so you can access the name :

$hive_count = DB::table('hives')
                  ->where('active','true')
                  ->join('hive_types', 'hives.hive_type_id', '=', 'hive_types.id')
                  ->groupBy('hive_type_id','hive_types.name')
                  ->selectRaw('sum(total) as sum, hive_types.name as name')
                  ->pluck('sum','name');
like image 100
Zakaria Acharki Avatar answered Nov 09 '22 19:11

Zakaria Acharki