2017-12-18 229 views
2

我創建一個回覆模型,然後試圖返回的對象與它的主人關係後負荷()。這裏是一個返回一個空對象的代碼:laravel預先加載()與創建父模型

//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'); 
} 

我不明白爲什麼。尋找澄清。

感謝, Yeasir

+1

https://stackoverflow.com/questions/26005994/laravel-with-method-versus-load-method這裏有一個很好的問題 – Sohel0415

回答

2

這是因爲,你應該使用with當你沒有對象,但(你正在查詢),當你已經有一個對象,你應該使用load

實例:

用戶集:

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

或:

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

單用戶

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

在Laravel

而且

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

方法實現,你可以看看with方法實現:

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

所以它開始新的查詢,所以實際上它不會執行查詢,直到您使用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()'。這裏最重要的事情是理解一個已經存在的對象實際上是一個查詢生成器,您可以使用它來進一步鏈接。非常感謝您的澄清。 –