我有两个表vouchers
和offers
。
报价表的字段为id, title
。
凭证表的字段为id, offer_id, title, original_price, off_price
。
表之间的关系是oneToMany。
如何在每个优惠中获得最大的优惠券百分比?
使用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