【发布时间】:2021-10-06 21:45:01
【问题描述】:
我很难解决我在 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() 它只是从显示空数组更改为 null;
我也尝试使用 where() 来过滤掉生成的空关系字段“animals”,但我收到错误消息说该字段不存在。
【问题讨论】: