【问题标题】:How to filter laravel model relationships where if the relationship is empty/null it should not show the object如何过滤 laravel 模型关系,如果关系为空/null,则不应显示对象
【发布时间】: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”,但我收到错误消息说该字段不存在。

【问题讨论】:

    标签: laravel eloquent model


    【解决方案1】:

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

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

    这是记录在here

    【讨论】:

    • 我确实尝试使用 has() 类似于您发送的内容和 whereHas() 但仍显示空/空字段。根据我对它的测试使用情况,不幸的是,我只能让它根据 UsersAnimalList 的基本关系模型进行过滤。虽然我希望它过滤的 Animals 模型的内部关系调用保持不变,但显示空/空字段。
    【解决方案2】:

    你可以做两件事:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-05-20
      • 2019-11-15
      • 1970-01-01
      • 2019-05-27
      • 2020-12-17
      • 1970-01-01
      相关资源
      最近更新 更多