问题
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');
}
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.
Thanks, Yeasir
回答1:
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
.
Examples:
Collection of users:
$users = User::with('profile')->get();
or:
$users = User::all();
$users->load('profile');
Single user:
$user = User::with('profile')->where('email','sample@example.com')->first();
or
$user = User::where('email','sample@example.com')->first();
$user->load('profile');
Methods implementation in Laravel
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
);
}
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.
来源:https://stackoverflow.com/questions/47868744/laravel-eager-loading-using-with-vs-load-after-creating-the-parent-model