laravel联接选择联接列的最大值



我有3个表产品,详细信息和detail_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.*

不能在关系上使用聚合函数吗?

$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');
}

最新更新