laravel在创建父模型后急于使用with()vs load()进行加载 [英] laravel eager loading using with() vs load() after creating the parent model
问题描述
我正在创建一个回复模型,然后尝试返回具有所有者关系的对象.这是返回空对象的代码:
I am creating a Reply model and then trying to return the object with it's owner relation. Here is the code that returns an empty object:
//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 关系,我会得到预期的结果.那就是返回的回复对象及其关联的所有者关系:
However, if i swap the with() method for load() method to load the owner relation, i get the expected result. That is the reply object is returned with it's associated owner relation:
//this works
{
$new_reply = $this->replies()->create($reply);
return $new_reply->load('owner');
}
我不明白为什么.寻找澄清.
i don't understand why. Looking for clarifications.
谢谢, Yeasir
Thanks, Yeasir
推荐答案
这是因为当您还没有对象(正在查询)时,应该使用with
;而当您已经有对象时,应该使用with
使用load
.
This is because you should use with
when you don't have object yet (you are making query), and when you already have an object you should use 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
方法的实现:
Also you can look at with
method implementation:
public static function with($relations)
{
return (new static)->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
}
因此它将开始新的查询,因此实际上直到您使用get
,first
等,它才会执行查询,而load
的实现方式如下:
so it's starting new query so in fact it won't execute the query until you use get
, first
and so on where is load
implementation is like this:
public function load($relations)
{
$query = $this->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
$query->eagerLoadRelations([$this]);
return $this;
}
因此它返回了相同的对象,但是它加载了该对象的关系.
so it's returning the same object, but it load relationship for this object.
这篇关于laravel在创建父模型后急于使用with()vs load()进行加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!