我正在尝试结合4种模型来获得摘要报告。这些是我的桌子。
user
-id
-name
-country_id
country
-id
-name
invoice
-id
-user_id
-type_id
type
-id
-name
我想根据国家/地区对每种类型的发票进行计数。就是这样。
country | type_name_1 | type_name_2 | type_name_2
America | 10 | 2 | 4
Canada | 62 | 0 | 35
China | 23 | 9 | 5
我尝试了以下查询,但没有完全给出我上面想要的答案。
\App\Invoice::all()->groupBy(function($s){
return $s->user->country->name;
})->groupBy(function($s){
return $s->type->count();
})
错误:此消息不存在消息“属性[type]”的异常 集合实例。”
有人可以给我指点吗?
答案 0 :(得分:0)
您的查询将仅获取Invoice
模型的结果。要获取相关表,请使用with
。
\App\Invoice::with('type','user')->get();
这将导致收集具有相关类型和用户的发票。然后,您可以使用groupBy方法来过滤结果集合。要了解有关groupBy方法的更多信息,请参见link。
答案 1 :(得分:0)
您必须查询国家模型,例如
Country::withCount(['invoice' => function($q){
$q->groupBy('type_id');
->get();