2017-01-18 10 views
2

我有一些Eloquent模型与对方之间存在关系,但是我希望只有在存在相关数据时才能设置这些关系。Laravel Eloquent:只有在存在相关数据时才设置关系

例如:

  • 部(模型) - >的hasMany - >工人(型号)(关系应 只设置如果部门相关人员,否则不设置)

这可能吗?我想这和horrably失败:(在系车型)

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 

我试图摆脱空阵列(例如:“工人”:[]),当他们没有相关数据时出现

+0

你想达到什么目的?只获得那些有工人或其他人的部门? –

+0

编辑帖子 –

+0

您的输出由您使用的查询进行管理。不是由你在'model'中定义的。 – Gayan

回答

1

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(); 

这是概念。为您的方案使用适当的代码。

+0

感谢您的回答!它的工作:) –

+0

很高兴你发现它很有帮助。感谢您是否可以将其标记为已接受并投票:) – Gayan

+0

我将其标记为已接受。但不幸的是,由于缺乏声望点,我无法赞成,对不起 –

0

只需添加关系并过滤收集到只有那些如下所示:

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

这样你只有部门至少包含一个工人。

+0

谢谢!完美工作,就像Gayan提供的解决方案 –