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

问题描述 投票:3回答:1

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

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

但是,如果我交换load()方法的load()方法来加载所有者关系,我得到预期的结果。这是与其关联的所有者关系返回的回复对象:

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

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

谢谢,Yeasir

php laravel-5 eloquent laravel-5.4 eager-loading
1个回答
2
投票

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

例子:

用户集合:

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

要么:

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

单用户:

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

要么

$user = User::where('email','[email protected]')->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;
}

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

© www.soinside.com 2019 - 2024. All rights reserved.