Laravel selectRaw具有连接表数据

时间:2022-02-05 17:03:05

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.

但是,我不希望对数组键使用hive_type_id,而是希望从hive_types表(列“name”)访问hive_type名称。我尝试了hive_type_id.name,但是这不起作用。

Models: Hive & HiveType

模型:蜂巢& HiveType

Thanks for your help.

谢谢你的帮助。

1 个解决方案

#1


2  

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

我想从hive_types表(列“name”)访问hive_type名称。

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

您必须在查询中加入表hive_types,以便访问名称:

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

Hope this helps.

希望这个有帮助。

#1


2  

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

我想从hive_types表(列“name”)访问hive_type名称。

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

您必须在查询中加入表hive_types,以便访问名称:

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

Hope this helps.

希望这个有帮助。