2017-12-18 232 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()'。这里最重要的事情是理解一个已经存在的对象实际上是一个查询生成器,您可以使用它来进一步链接。非常感谢您的澄清。 –