2017-07-28 68 views
1

我有这样的代码:Laravel和algolia,忽略数组,如果空

public function toSearchableArray() 
{ 
    $data = $this->toArray(); 
    $data['_geoloc'] = $this->_geoloc->toArray(); 
    $data['address'] = $this->address->toArray(); 
    return $data; 
} 

但是有时$数据[ '实体']为空,因此引发我一个错误:

[Symfony\Component\Debug\Exception\FatalThrowableError] 
    Call to a member function toArray() on null 

有什么该如何绕过?

回答

2

你需要的,如果存在的话,检查内容和之前对它们调用方法不为空,这样的:

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();

+0

爱你谢谢!!!! –

0

我想你可以试试这个:

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; 

} 

你希望帮助!

+0

仍然抛出methe同样的错误 –

+0

$ data = $ this-> toArray();是不是空的,但$ data ['address']是 –

+0

@PrzemekWojtas请检查我的更新回答 –

1

我假设地址是与另一个表的关系。

指定者()将其转换,如果它之前

public function toSearchableArray() 
{ 
    $this->address; 

    $data = $this->toArray(); 

    return $data; 
} 

加载的_geoloc也到另一个表的关系?