laravel 创建父模型后使用 with() 与 load() 进行预加载
laravel eager loading using with() vs load() after creating the parent model
我正在创建一个 Reply 模型,然后尝试 return 对象与它的 owner 关系。这是 return 空对象的代码:
//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 关系,我得到了预期的结果。也就是说,回复对象是 return 与其关联的 owner 关系:
//this works
{
$new_reply = $this->replies()->create($reply);
return $new_reply->load('owner');
}
我不明白为什么。寻求澄清。
谢谢,
耶斯
这是因为当你还没有对象时(你正在查询)你应该使用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
);
}
所以它开始新的查询所以实际上它不会执行查询,直到你使用 get
、first
等等 load
实现是这样的:
public function load($relations)
{
$query = $this->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
$query->eagerLoadRelations([$this]);
return $this;
}
所以它返回同一个对象,但它加载了该对象的关系。
我正在创建一个 Reply 模型,然后尝试 return 对象与它的 owner 关系。这是 return 空对象的代码:
//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 关系,我得到了预期的结果。也就是说,回复对象是 return 与其关联的 owner 关系:
//this works
{
$new_reply = $this->replies()->create($reply);
return $new_reply->load('owner');
}
我不明白为什么。寻求澄清。
谢谢, 耶斯
这是因为当你还没有对象时(你正在查询)你应该使用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
);
}
所以它开始新的查询所以实际上它不会执行查询,直到你使用 get
、first
等等 load
实现是这样的:
public function load($relations)
{
$query = $this->newQuery()->with(
is_string($relations) ? func_get_args() : $relations
);
$query->eagerLoadRelations([$this]);
return $this;
}
所以它返回同一个对象,但它加载了该对象的关系。