Laravel如何在hasMany关系为空时返回值NULL

问题描述

在我的let data = [{uniqueid:200,name:'sandesh',loop:222,salary:2500,},{uniqueid:300,name:'hello',name:'hello1',] const formattedData = (data) => { const result = data.reduce((res,d) => { if(res[d.uniqueid]) { res[d.uniqueid].data.push(d); } else { res[d.uniqueid] = { uniqueid: d.uniqueid,data: [ {...d} ] } } return res; },{}) ; return Object.values(result); } console.log(formattedData(data))应用程序中,当我的HasMany模型返回一个空数组时,我想返回值laravel!我该如何实现?

我试图这样做:

null

但仍然返回

public function something(){
  $collection = $this->hasMany('App\Models\SomeModel');
  return $collection ? $collection : null
}

但是我希望显示它:

{
   something: []
}

那么,有人可以帮我吗?

解决方法

您可以像这样使用函数count()

return count($collection) > 0 ? $collection : null;