我有一些Eloquent模型彼此有关系,但我希望只有相关数据存在才能设置这些关系。
例如:
部门(型号) - > hasMany - >工人(模型)(关系应该是 只有当部门有相关工人时才设置,否则不设置)
有可能吗?我试过这个并且失败了:(在部门模型中)
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"
}
}
当部门有工人时,everthing按预期工作:
{
"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":[]),当它们没有相关数据时出现
答案 0 :(得分: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();
这是概念。为您的方案使用适当的代码。
答案 1 :(得分:0)
只需添加关系并将收集过滤到仅包含工作人员的关系,如下所示:
$departments = Department::with('workers')->filter(function($department) {
return ! is_null($department->workers)
});
这样,您只有包含至少一个工作人员的部门。