[英]Laravel how to return the value NULL when hasMany relationship is empty
In my laravel
-application I want to return the value null
when my HasMany-model returns an empty array!在我的laravel
当我的 HasMany 模型返回一个空数组时,我想返回null
值! How can I achieve that?我怎样才能做到这一点?
I tried to do this:我试图这样做:
public function something(){
$collection = $this->hasMany('App\Models\SomeModel');
return $collection ? $collection : null
}
but that still returns但这仍然返回
{
something: []
}
but I want this to be displayed:但我希望显示这个:
{
something: null
}
so, can someone help me out?所以,有人可以帮我吗?
您可以像这样使用函数count()
:
return count($collection) > 0 ? $collection : null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.