Laravel Eloquent,如何使用 where 访问 3 个表上的 eloquent?

Laravel Eloquent, How to access eloquent on 3 tables with where?

我有 3 个这样的表:

Items table
id | name
1  | Laptop
2  | Computer
3  | Tv

Production table
id | date
1  | 2021-10-01
2  | 2021-10-03
3  | 2021-10-30

Detail table
id | production_id| item_id |qty
1  | 1            | 1       | 5 
2  | 1            | 3       | 10
 
3  | 2            | 1       |2
4  | 2            | 2       |3
5  | 2            | 3       |23

我想要实现的是这样的:

(where Production dateBetween this date and that date)
Items       |Sum qty 
Laptop      | 7
Computer    | 3
Tv          | 33

如何以 eloquent 方式做到这一点?

我应该使用 hasManyThrough 关系吗?

感谢您的帮助。

由于这是连接问题,我不会为此使用标准关系。相反,让 mysql 通过在 ORM.

中创建自定义查询来解决这个问题

策略是连接所有行,按产品名称分组。对数量求和并为日期创建 where 条件。

$items = Item::select('name', DB::raw('SUM(details.qty) as quantity'))
    ->join('details', 'items.id', '=', 'details.item_id')
    ->join('productions', 'productions.id', '=', 'details.production_id')
    ->whereBetween('productions.date', [now()->subMonth(), now())
    ->groupBy('details.name')
    ->get();

你可以像这样循环数据。

foreach ($items as $item) {
    $item->name;
    $item->quantity;
}