2017-01-18 9 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提供的解決方案 –