【问题标题】:Selecting the maximum discount percent of vouchers' price of every offer选择每个优惠的优惠券价格的最大折扣百分比
【发布时间】:2020-01-14 08:55:48
【问题描述】:

我有两张桌子vouchersoffers

报价表字段为id, title

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

表之间的关系是oneToMany

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

【问题讨论】:

  • '凭证百分比,?'你想定义这个吗?
  • Yeeeeeeeeeeeeeeees

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


【解决方案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();
}

【讨论】:

    【解决方案2】:

    使用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
    

    【讨论】:

    • 如何获取包含前最大百分比优惠券的优惠列表?
    • @SaeedNikookalam 你建立了关系vouchers()
    • Yeeeeeeeeeeeeeees
    • @SaeedNikookalam 好的,你怎么知道它不起作用。有任何错误信息吗?你能给我一些信息吗?
    • 追加max_discount字段时结果没有变化。
    猜你喜欢
    • 2012-12-27
    • 2017-10-08
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多