在创建父模型后使用with()vs load()进行laravel eager loading

时间:2017-12-18 12:41:25

标签: php laravel-5 eloquent laravel-5.4 eager-loading

我正在创建回复模型,然后尝试使用所有者关系返回该对象。这是返回空对象的代码:

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

但是,如果我将 with()方法替换为 load()方法来加载所有者关系,我会得到预期的结果。也就是说,回复对象与其关联的所有者关系返回:

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

我不明白为什么。寻找澄清。

谢谢, Yeasir

1 个答案:

答案 0 :(得分:2)

这是因为当你还没有对象(你正在进行查询)时应该使用with,当你已经拥有一个对象时,你应该使用load

示例:

用户集合

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

或:

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

单个用户

$user = User::with('profile')->where('email','sample@example.com')->first();

$user = User::where('email','sample@example.com')->first();
$user->load('profile');

Laravel中的方法实现

另外,您可以查看with方法实现:

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

所以它开始新的查询,所以事实上在你使用getfirst之后它不会执行查询等等load实现是这样的:

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

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

    return $this;
}

所以它返回相同的对象,但它加载了该对象的关系。