我有如下 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
如何以雄辯的方式做到這一點?
我應該使用 hasManyThrough 關系嗎?
謝謝你的熱心幫助。
uj5u.com熱心網友回復:
由于這是連接問題,因此我不會為此使用標準關系。相反,讓我們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');
你可以像這樣回圈資料。
foreach ($items as $item) {
$item->name;
$item->quantity;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343340.html
上一篇:將關聯陣列存盤到資料庫中
