Laravel eloquent 如何获取不为NULL的最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37761870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel eloquent how to get the minimum value that is not NULL?
提问by Harrison
This is the code in my Product
model to get the minimum price value (one product can have multiple price)
这是我的Product
模型中获取最低价格值的代码(一个产品可以有多个价格)
public function getLowestAttribute ()
{
return $this->prices->min('price');
}
But it will return NULL
rather than the smallest integer if there is a NULL
.
但是NULL
如果有一个,它将返回而不是最小的整数NULL
。
Basically I want to achieve this:
基本上我想实现这个:
[1, NULL, 2]
returns 1
[1, NULL, 2]
回报 1
[1, NULL, 0]
returns 0
[1, NULL, 0]
回报 0
Any suggestion would be appreciated.
任何建议将不胜感激。
回答by Harrison
I found filter
, and it works now.
我找到了filter
,现在可以使用了。
public function getLowestAttribute ()
{
$prices = $this->prices->filter(function ($item) {
return !is_null($item->price);
});
return $prices->min('price');
}
回答by KuKeC
Have you tried maybe
你有没有试过
public function getLowestAttribute ()
{
return $this->prices->where('price','>=',0)->min('price');
}
回答by Efigie
A fix to the KuKeC answer would be
KuKeC 答案的修复将是
public function getLowestAttribute()
{
return $this->prices->where('price', '!==', null)->min('price');
}