首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel Eloquent,如何用where访问3个表上的eloquent?

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

Stack Overflow用户
提问于 2021-10-30 18:13:12
回答 1查看 57关注 0票数 1

我有3个类似下面的表格:

代码语言:javascript
复制
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

我试图实现的是这样的:

代码语言:javascript
复制
(where Production dateBetween this date and that date)
Items       |Sum qty 
Laptop      | 7
Computer    | 3
Tv          | 33

如何以雄辩的方式做到这一点?

我应该使用hasManyThrough关系吗?

谢谢你的好意帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-30 21:04:58

因为这是一个连接问题,所以我不会使用标准关系。相反,让mysql通过在ORM中创建自定义查询来解决此问题。

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

代码语言:javascript
复制
$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();

你可以像这样循环数据。

代码语言:javascript
复制
foreach ($items as $item) {
    $item->name;
    $item->quantity;
} 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69780918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档