带有连接表数据的 Laravel selectRaw

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40964201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:52:12  来源:igfitidea点击:

Laravel selectRaw with joined table data

phpmysqllaravellaravel-5

提问by Pedro

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 表(列“名称”)访问 hive_type 名称。我试过 hive_type_id.name 但这没有用。

Models: Hive & HiveType

型号:Hive 和 HiveType

Thanks for your help.

谢谢你的帮助。

回答by Zakaria Acharki

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

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

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

您必须hive_types在查询中加入该表,以便您可以访问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');