2017-12-22 20 views
0

laravel 5.5에서 외부 키를 사용하여 다른 모델과 연결된 모델을 제공하는 경우 두 속성의 전체 조인 결과를 얻을 수 있다는 것을 이해하려고합니다. 모델. 내가 wanto 두 모델을 반환하고 그들을 병합 피하기 위해. 내 모델의 코드를 아래laravel 5.5 model relation in json

: 컨트롤러에서

class Event extends Model { 
    public function location(){ 
     return $this->hasOne('App\Location'); 
    } 
} 

나는 각각의 이벤트의 위치 정보를 얻을 수 있지만, 결과에 나는 이벤트 및 위치 모두의 정보를보고 싶습니다. 내가 ORM과 모델을 호출하는 경우 컨트롤러에서

:

$event = Event::where('name',$name)->first()->location; 

    $model=$eventLocation->getModel(); 
    return $model; 

그리고이 아니라 이벤트의 위치의 속성 만 포함

{"id":12,"created_at":null,"updated_at":null,"name":"location_test","event_id":"1"} 

으로이 JSON을 얻을! 둘 다 어떻게 보여줄 수 있습니까? 당신이 이벤트 자체와 location 필드로 전체 관련 위치를 얻을 것이다 이런 식으로

$event = Event::with('location')->where('name', $name)->first(); 
$location = $event->location; 

:와

감사

답변

1

보십시오.

문서의 Eager Loading 섹션을 참조하십시오.

+0

볼 수 있습니다 얻고 싶은 경우에

내가 이벤트에 대한 유일한 위치에 대한 정보,의 속삭임을 얻을 ... – user8958651

+0

이벤트는 내부에'$ event' 변수는 속성을 가지고 그것을 액세스 할'위치'. '$ Event-> toJson (')과 같이'$ Event' 컬렉션에서'toJson' 또는'toArray'와 같은 ['Collection'] (https://laravel.com/docs/5.5/collections) 메소드를 사용하여 모든 것을 읽을 수 있습니다.)'. –

0

이을 시도 할 때 다음

$event = Event::where('name',$name)->first(); 
$event->load('location'); 

:

$event = Event::with('location')->where('name',$name)->first(); 

나 :

$event = Event::with('location')->where('name', $name)->first(); 

return $event->toJson(); 

당신은 당신이 사용할 수있는 data.location

+0

좋아요, 작동합니다. – user8958651