Laravel Eloquent: 仅当相关数据存在时才设置关系

Laravel Eloquent: Set relationships only if related data exists

我有一些 Eloquent 模型相互关联,但我希望仅当相关数据存在时才设置这些关系。

例如:

可能吗?我尝试了这个但失败了:(在部门模型中)

public function worker() {

     $model = new Department();

     if(isset($model->relations)) {
         return $this->hasMany(Worker::class, 'wrk_department_id');
        }
    }

//编辑:

当部门没有工人时,我的输出是这样的:

{
"data": {
    "type": "department",
    "id": "8",
    "attributes": {
        "accessory": [],
        "department": "Marketing",
        "department_id": 8,
        "dept_floor_id": 2,
        "inventory": [],
        "software": [],
        "worker": []
    },
    "links": {
        "self": {
            "href": "http://127.0.0.1:8000/api/v2/department/8"
        }
    }
},
"links": {
    "self": {
        "href": "http://127.0.0.1:8000/api/v2/department/8"
    }
},
"jsonapi": {
    "version": "1.0"
}

}

当部门有工作人员时,一切正常:

{
"data": {
"type": "department",
"id": "1",
"attributes": {
  "department": "Entwicklung",
  "department_id": 1,
  "dept_floor_id": 3
},
"links": {
  "self": {
    "href": "http://127.0.0.1:8000/api/v2/department/1"
  }
},
"relationships": {
  "worker": {
    "data": [
      {
        "type": "worker",
        "id": "5"
      },
      {
        "type": "worker",
        "id": "8"
      },
      {
        "type": "worker",
        "id": "11"
      },
      {
        "type": "worker",
        "id": "13"
      }, //and so on

我正在尝试摆脱空数组(例如:"worker":[]),它们在没有相关数据时出现

只需添加关系并将集合过滤为仅包含工人的集合,如下所示:

$departments = Department::with('workers')->filter(function($department) {
        return ! is_null($department->workers)
    });

这样您就只有包含至少一名工人的部门。

Department 模型中添加关系。

public function worker() {
    return $this->hasMany(Worker::class, 'wrk_department_id');
}

并且当您在 method 内部查询时 your-controller

$builder = Department::with('other-relationships');
If('your-condition-check') {
     $builder-with('workers');
}
$model = $builder->get();

这是概念。为您的场景使用适当的代码。