Laravel中具有属性的最小和最大

时间:2018-12-04 14:18:07

标签: php laravel model sum

我有一个带有属性的产品模型。

public function getFinalPriceAttribute()
{
    if ($this->discount_type == 1) {
        return $this->price -= $this->discount;
    } elseif ($this->discount_type == 0) {
        return $this->price * (1 - $this->discount / 100);
    }

    return $this->price;
}

我需要获取类别中产品的最小和最大总和。我可以做到:

$minsumm = $products->min('price');
$maxsumm = $products->max('price');

在数据库中所有产品的products集合中。如何使用属性finalPrice?

获得最低和最高价格

2 个答案:

答案 0 :(得分:1)

函数minmax允许将闭包传递给它们。因此,您可以执行以下操作:

$minsumm = $products->min(function ($prod) { return $prod->finalPrice; });
$maxsumm = $products->max(function ($prod) { return $prod->finalPrice; });

答案 1 :(得分:0)

尝试

$products = Product::get();
$minPrice = $product->min('final_price');
$maxPrice = $product->max('final_price');

别忘了在产品模型中添加$ appends

protected $appends = ['final_price'];