我有一些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
我试图摆脱空阵列(例如:“工人”:[]),当他们没有相关数据时出现
你想达到什么目的?只获得那些有工人或其他人的部门? –
编辑帖子 –
您的输出由您使用的查询进行管理。不是由你在'model'中定义的。 – Gayan