【问题标题】:Get sum of nested Collection failed Laravel Eloquent获取嵌套集合的总和失败 Laravel Eloquent
【发布时间】:2019-07-25 19:53:34
【问题描述】:

我需要嵌套关系集合的总和。当我尝试此代码时,找不到该字段。

  return Offer::where("id", $offer_id)
    ->with(['rooms.products' => function($sql) use ($product_id) {
        $sql->where('product_id', $product_id);
    }]
    )->sum("value");

值字段存在于 rooms.products 表中。

提前致谢

【问题讨论】:

  • 你能用get显示那个查询的结果吗?

标签: laravel eloquent nested relationship


【解决方案1】:

现在,sum() 方法将在offers 表中查找value 列,而您需要products 表中的值。试试这个方法:

return Product::where('product_id', $product_id)
    ->whereHas('room.offer', function($sql) use ($offer_id) {
        $sql->where("id", $offer_id)
    })->sum("value");

【讨论】:

  • 这工作正常,但在产品表中有数千个具有相同产品 ID 的条目。这不是我认为最优雅的解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 2020-10-22
  • 2019-05-19
  • 2018-12-27
相关资源
最近更新 更多