Laravel Eloquent:在返回时忽略空值

时间:2017-11-10 10:32:09

标签: php laravel laravel-5 eloquent

我想修改我的雄辩查询,只获取json值,其中family.equipment与null不同。

这是我的要求:

$data = Ov::with([
    'name',
    'family.equipment' => function ($query) use ($model) {
        $query->where('model', 'like', $model)->orWhere('baseModel', 'like', $model);
    },
    'family.device.equipment' => function ($query) use ($model) {
        $query->where('model', 'like', $model)->orWhere('baseModel', 'like', $model);
    }
])->distinct()->get();

实际结果:

返回:

[
  {
    "name": [
      {
        "label": "LIC",
        "value": "@ew9Ddededezdzec"
      }
    ],
    "family": [
      {
        "name": "test1",
        "equipment": null,
        "device": []
      },
      {
        "name": "test2",
        "equipment": null,
        "device": []
      },
      {
        "name": "test3",
        "equipment": {
            'name': "test",
        }
        "device": []
      },
    ]
  },...
]

4 个答案:

答案 0 :(得分:0)

使用ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"

whereNotNull

答案 1 :(得分:0)

您可能需要添加filter方法调用。

$data = Ov::with([
    'name',
    'family.equipment' => function ($query) use ($model) {
        $query->where('model', 'like', $model)->orWhere('baseModel', 'like', $model);
    },
    'family.device.equipment' => function ($query) use ($model) {
        $query->where('model', 'like', $model)->orWhere('baseModel', 'like', $model);
    }
])->distinct()->filter()->get();

答案 2 :(得分:0)

您正在寻找haswhereHas。见Docs - querying-relationship-existence

Ov::has('family.equipment')-> ...

答案 3 :(得分:0)

您可以尝试使用has方法来消除空设备,然后执行连接:

let fetchRequest:NSFetchRequest<T> = T.fetchRequest() as! NSFetchRequest<T>\\ line return nil. There is no crash below iOS 10.x.