서로 관계가있는 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
빈 배열 (예 : "worker": [])을 제거하려고합니다. 관련 데이터가없는 경우에 표시됩니다.
달성하려는 목표는 무엇입니까? 사업에 종사하는 부서 또는 다른 부서 만 받습니까? –
게시물 수정 –
출력 결과는 사용하는 쿼리에 의해 결정됩니다. '모델'에서 정의한 것에 의해서가 아닙니다. – Gayan