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

时间:2020-01-14 08:55:48

标签: mysql laravel greatest-n-per-group

我有两个表vouchersoffers

要约表的字段为id, title

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

表之间的关系为 oneToMany

如何在每项优惠中获得最高优惠券百分比?

2 个答案:

答案 0 :(得分:1)

protected $appends = ['max_discount_voucher'];
public function getMaxDiscountVoucherAttribute()
{
    return $this->vouchers
        ->select('*', \DB::raw('100 - ( new_price * 100 ) / old_price AS discount_percent'))
        ->orderByDesc('discount_percent')
        ->first();
}

答案 1 :(得分:0)

使用accessor很容易。

在您的优惠模型中:

Root

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

protected $appends = ['max_discount'];

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