【问题标题】:laravel join select max of joined columnlaravel join 选择连接列的最大值
【发布时间】:2021-09-12 09:12:52
【问题描述】:

我有 3 张桌子 productsdetailsdetail_colors

我想要select max "stock" from "detail_colors"max "price" from "details"

$products = Product::
           join('details', function (JoinClause $join) {
               $join->on('products.id', '=', 'details.product_id');

           })
           ->join('detail_colors', function (JoinClause $join) {
               $join->on('products.id', '=', 'detail_colors.product_id');
           })
           ->select('products.*', DB::raw('max(details.price) as price'), DB::raw('max(detail_colors.stock) as stock'))

它不工作。

我使用 laravel 8.*

【问题讨论】:

  • 你不想使用雄辩的模型和关系吗?
  • 你需要添加 ->get() 来结束
  • 我的问题没有添加 ->get();我的问题是我无法从另一个表中选择最大值。
  • @shaedrich 我使用关系。因为我需要从另外两张桌子上按价格和库存订购。我使用了加入。
  • 你得到的输出是什么?

标签: php laravel laravel-8 laravel-query-builder


【解决方案1】:

你不能对关系使用聚合函数吗?

$products = Product::query()
           ->withMax('details', 'price')
           ->withMax('detail_colors', 'stock')

或者你可以这样定义关系:

public function details()
{
    return $this->hasOne(Details::class)->ofMany('price', 'max');
}
public function details()
{
    return $this->hasOne(DetailColors::class)->ofMany('stock', 'max');
}

【讨论】:

  • 不客气。很高兴我能帮助你。只是出于好奇:您选择了两个选项中的哪一个?
  • 我有很多关系。我从来没有见过聚合函数。只是我使用功能。谢谢
猜你喜欢
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多