我不知道该怎么做才能解决这个问题我在 Laravel 中遇到的模型关系的结果返回空/空关系字段,而我只希望它在执行 GET 时显示带有数据的“动物”使用搜索字符串调用。例如,在下面“favorite_animals”字段的响应中,我只希望带有数据的“animals”对象显示在该数组中。
这是端点 localhost/api/v1/lists/2?search=honeybadger
"name": "titleTwo","description": "list two","favorite_animals": [
{
"animals": null
},{
"animals": {
"id": 1,"name": "HoneyBadger","description": "dgaf","created_at": "2021-07-30T22:49:36.000000Z","updated_at": "2021-07-30T22:49:36.000000Z"
}
},{
"animals": null
}
]
以下是控制器中查询模型数据的代码块:
$list = UsersAnimalList::with(['favoriteAnimals.animals' => function($query) use($request){
$query->where('name','like',$request->input('search'));}])->get();
以下是模型关系:
模型:UserAnimalList
public function favoriteAnimals(){
return $this->hasMany(UsersFavoriteAnimals::class,'list_id','id');}
模型:UsersFavoriteAnimals
public function animals(){
return $this->hasOne(Animals::class,"id","animals_id");}
其他模型但没有关联方法:动物
我尝试过使用 has() 但它返回了一个空响应。 我尝试将关系从 hasMany() 更改为 hasOne() 它只是从显示空数组更改为空数组;
我还尝试使用 where() 尝试过滤掉空生成的关系字段“animals”,但我收到错误消息,指出该字段不存在。