Reputation: 305
I would like to know if after:
$post = Post::find(1);
$author = new Author($someData);
$post->author()->save($author);
the following code is lazy loading the author?
$authorName = $post->author->name;
To clarify Post an Author have a OneToOne relation.
If I use:
dump($post);
the output does not contain the author and shows this:
#relations: []
Same result using $post->author()->createMany() method
So I want to be sure it does not make an extra query to load the author since I have it in memory already.
laravel/framework: 5.4.*
Upvotes: 0
Views: 251
Reputation: 4499
You can do something like this if you really want to. You can use setRelation
.
$post = Post::find(1);
$author = Author::create($someDataWithPostId); // save the author instance to the database.
$post->setRelation('author', $author); // set relation method will set the author as author relation.
Now when you access $authorName = $post->author->name;
it will not load from the database since we have already set the author relation to the data to the post.
Upvotes: 1
Reputation: 91
Try Eager Loading by with function example
$post= Model::with('author')->find(id);
then let your one To One Relational method Name is "author" in post model
you can find it by dd($post->author->name)
Upvotes: 0