【问题标题】:laravel eager loading using with() vs load() after creating the parent model创建父模型后使用 with() 与 load() 的 laravel 急切加载
【发布时间】:2018-05-31 19:30:02
【问题描述】:

我正在创建一个 Reply 模型,然后尝试返回具有 owner 关系的对象。以下是返回空对象的代码:

//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() 方法来加载 owner 关系,我会得到预期的结果.也就是说,回复对象与其关联的 owner 关系返回:

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

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

谢谢, 是的

【问题讨论】:

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


【解决方案1】:

这是因为当你还没有对象(你正在查询)时你应该使用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;
}

所以它返回的是同一个对象,但是它为这个对象加载了关系。

【讨论】:

  • 优秀。函数定义很清楚。因此,要获得与 load 函数相同的结果,必须像这样:return $new_reply->with('owner')->latest()->first()。这里重要的是要理解一个已经存在的对象实际上是一个查询构建器,您可以使用它来进一步链接。非常感谢您的澄清。
猜你喜欢
  • 2013-05-16
  • 2020-09-12
  • 2023-03-20
  • 1970-01-01
  • 2017-09-17
  • 2019-07-08
  • 2013-06-10
  • 2020-09-08
  • 2013-03-27
相关资源
最近更新 更多