Reputation: 2371
Eager Loading Multiple Relationships
books = Book::with(['author', 'publisher'])->get();
Nested Eager Loading
$books = Book::with('author.contacts')->get();
Eager Loading Specific Columns
$books = Book::with('author:id,name,book_id')->get();
How to Nested Eager Loading Specific Columns?
I try this code below but seems not working properly.
$books = Book::with('author:id,name,book_id, author.contacts:id,name,author_id')->get();
Upvotes: 0
Views: 52
Reputation: 2371
In order to make query cheap and fast, we should only fetch column that we need. And for any reason, eager loading is good because we only retrieve data once instead of using foreach.
$data = Podcast::with(["comments" => function ($query) {
$query->select('id', 'podcast_id', 'comment', 'user_id');
},"comments.users" => function ($query) {
$query->select('id', 'name');
},"likes" => function ($query) {
$query->select('id','podcast_id', 'count');
}])->get(['id', 'title', 'author']);
Don't forget to select 'id'
on Podcast model because it used to be primary key.
Also, don't forget to select 'podcast_id'
on Comment model because it used to be foreign key.
Even if Comment belongs to many User, you still can fetch it as long as you select 'user_id'
on Comment model.
Upvotes: 3