0

我正在尝试结合 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();
})

错误:带有消息“此集合实例上不存在属性 [类型]”的异常。

有人可以在这里给我指点吗?

4

2 回答 2

0

您的查询将仅获得Invoice模型的结果。要获取相关表,请使用with.

\App\Invoice::with('type','user')->get();

这将收集具有相关类型和用户的发票。然后可以使用 groupBy 方法过滤结果集合。要了解有关 groupBy 方法的更多信息,请参阅链接

于 2018-11-19T05:21:06.857 回答
0

您必须查询国家模型,例如

    Country::withCount(['invoice' => function($q){
          $q->groupBy('type_id');
     ->get();
于 2018-11-19T07:09:43.497 回答