2017-12-18 2 views
2

응답 모델을 만든 다음 소유자 관계로 객체를 반환하려고합니다. 여기에 빈 개체를 반환하는 코드는 다음과 같습니다 그러나부모 모델을 만든 후 with() vs load()를 사용하여 로딩하기

//file: Thread.php 
//this returns an empty object !!?? 
public function addReply($reply) 
{ 
    $new_reply = $this->replies()->create($reply); 
    return $new_reply->with('owner'); 
} 

, 나는 내가 예상 결과를 얻을 수는 소유자 관계를로드 할() 부하 방법() 방법으로 을 교환합니다. 난 왜 이해가 안

//this works 
{ 
    $new_reply = $this->replies()->create($reply); 
    return $new_reply->load('owner'); 
} 

: 즉, 반환되는 응답 객체가 소유자에게 관계를 연관된이다. 설명을 찾고 있습니다. 당신이 with를 사용해야하기 때문에

감사합니다, Yeasir

+1

https://stackoverflow.com/questions/26005994/laravel-with-method-versus-load-method 여기에 문제의 멋진 세부 사항이 있습니다. – Sohel0415

답변

2

이 당신이 (당신이 질의를하고 있습니다) 아직 개체가없는, 당신은 이미 개체가있을 때 당신이 load을 사용해야 할 때입니다.

예 : 사용자의

컬렉션 :

$users = User::with('profile')->get(); 

나 :

$users = User::all(); 
$users->load('profile'); 

단일 사용자 :

$user = User::with('profile')->where('email','[email protected]')->first(); 
0 실제로는 실행되지 않도록이 새 쿼리를 시작 그래서

public static function with($relations) 
{ 
    return (new static)->newQuery()->with(
     is_string($relations) ? func_get_args() : $relations 
    ); 
} 

: 또한

Laravel에서

또는

$user = User::where('email','[email protected]')->first(); 
$user->load('profile'); 

방법 구현 당신은 with 메소드 구현을 볼 수 있습니다 get, first 등을 사용할 때까지 쿼리는 load인데 다음과 같습니다.

public function load($relations) 
{ 
    $query = $this->newQuery()->with(
     is_string($relations) ? func_get_args() : $relations 
    ); 

    $query->eagerLoadRelations([$this]); 

    return $this; 
} 

그래서 동일한 객체를 반환하지만이 객체에 대한로드 관계입니다.

+0

우수합니다. 함수 정의는 그것을 명확하게 만들었다. 따라서 ** load ** 함수와 같은 결과를 얻으려면'return $ new_reply-> ('owner') -> latest() -> first()'와 같이해야합니다. 여기에서 중요한 것은 이미 존재하는 객체가 실제로 추가 체인에 사용할 수있는 쿼리 작성기임을 이해하는 것입니다. 명확히 해 주셔서 감사합니다. –

관련 문제