是否可以在toSearchableArray
关系字段中进行映射?我的意思是,有了用户模型,我试着在相关的模型字段中搜索,比如;
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
return [
'name' => $this->name,
'plz' => $this->account->zip,
];
}
/**
* @return HasOne
*/
public function account(): HasOne
{
return $this->hasOne(Member::class);
}
在控制器中搜索结果
if($request->has('s')) {
$founds = User::search($request->get('s'))->get();
}
将抛出Attempt to read property "zip" on null
我真的没有在文档中找到任何与这个问题相关的信息
我确实有两种方法,其中一种我认为是粗糙的。
方法1:下面是一个示例实现,其中您正在搜索所有一个模型,然后搜索关系(帐户)
public function toSearchableArray()
{
$array = $this->toArray();
$array = $this->transform($array);
$array['country'] = $this->countries->map(function ($data) {
return $data['name'] ?? '';
})->toArray();
return $array;
}
方法2:public function toSearchableArray()
{
$array = $this->toArray();
// Customize array...
$array = [
'user_name' => $this->user_name,
'country' => $this->getCountryNameById($this->country_id),
...
];
return $array;
}
中的关系是在helper中定义的,或者你可以创建一个单独的trait,并将它导入到model with method中。在这里,国家关系在模型中定义为
//Get Country name By id
function getCountryNameById($id) {
$country = AppCountry::select('name')->find($id);
return $country->name ?? '';
}