Laravel 和 algolia,如果为空则忽略数组
Laravel and algolia, ignore array if null
我有这个代码:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
return $data;
}
但是有时 $data['entities'] 为 null 因此抛出一个错误:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function toArray() on null
有什么方法可以绕过它吗?
我想你可以试试这个:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
print('<pre style="color:red;">');
print_r($data);
print('</pre>');
exit;
return $data;
}
希望对你有所帮助!!!
我假设地址是与另一个地址的关系 table。
toArray() 将转换它,如果它在
之前被加载
public function toSearchableArray()
{
$this->address;
$data = $this->toArray();
return $data;
}
_geoloc 是否也与另一个 table 有关系?
在对元素调用方法之前,您需要检查元素是否存在且不为空,如下所示:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = !empty($this->_geoloc) ? $this->_geoloc->toArray() : null;
$data['address'] = !empty($this->address) ? $this->address->toArray() : '';
return $data;
}
同时 $this->toArray();
会将模型实例转换为包含所有关系的数组。所以你需要像这样加载它们:$this->load('_geoloc', 'address');
并且只调用 $data = $this->toArray();
我有这个代码:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
return $data;
}
但是有时 $data['entities'] 为 null 因此抛出一个错误:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function toArray() on null
有什么方法可以绕过它吗?
我想你可以试试这个:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
print('<pre style="color:red;">');
print_r($data);
print('</pre>');
exit;
return $data;
}
希望对你有所帮助!!!
我假设地址是与另一个地址的关系 table。
toArray() 将转换它,如果它在
之前被加载public function toSearchableArray()
{
$this->address;
$data = $this->toArray();
return $data;
}
_geoloc 是否也与另一个 table 有关系?
在对元素调用方法之前,您需要检查元素是否存在且不为空,如下所示:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = !empty($this->_geoloc) ? $this->_geoloc->toArray() : null;
$data['address'] = !empty($this->address) ? $this->address->toArray() : '';
return $data;
}
同时 $this->toArray();
会将模型实例转换为包含所有关系的数组。所以你需要像这样加载它们:$this->load('_geoloc', 'address');
并且只调用 $data = $this->toArray();