如何过滤 Laravel 模型关系,如果关系为空/空,则不应显示对象

我不知道该怎么做才能解决这个问题我在 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”,但我收到错误消息,指出该字段不存在。

pjdontcry 回答:如何过滤 Laravel 模型关系,如果关系为空/空,则不应显示对象

您可以做两件事:

  1. 使用 laravel 内置的 toArray() 方法返回数组中的值,然后使用 php array_filter() 函数删除空值

  2. 您可以创建一个 collection 并使用 Laravel 内置的 filter() 函数从数据集合中删除空值

,

您还可以根据关系的存在来过滤模型:

$list = UsersAnimalList::with(['favoriteAnimals.animals' => function($query) use($request) {
    $query->where('name','like',$request->input('search'));
}])->has('favoriteAnimals.animals')->get();

这是记录在案的here

本文链接:https://www.f2er.com/3766.html

大家都在问