我有一些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