选择每个优惠券价格的最大折扣百分比

问题描述 投票:0回答:1

我有两个表vouchersoffers

报价表的字段为id, title

凭证表的字段为id, offer_id, title, original_price, off_price

表之间的关系是oneToMany

如何在每个优惠中获得最大的优惠券百分比?

mysql laravel greatest-n-per-group
1个回答
0
投票

使用accessor将很容易。

在您的优惠模型中:

protected $appends = ['max_discount'];

public function getMaxDiscountAttribute()
{
    return $this->vouchers()
               ->selectRaw('MAX(off_price - original_price) AS max_discount')
               ->first()
               ->max_discount;
}

您可以使用以下属性获得报价:

$offers = Offer::where(...)->get(); // return the eloquent.
$offers->first()->max_discount; // return the maximum discount
© www.soinside.com 2019 - 2024. All rights reserved.