我有两个表vouchers
和offers
。
要约表的字段为id, title
。
凭证表的字段为id, offer_id, title, original_price, off_price
。
表之间的关系为 oneToMany 。
如何在每项优惠中获得最高优惠券百分比?
答案 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;
}