Elbo Shindi Pangestu
Elbo Shindi Pangestu

Reputation: 2371

How to use Laravel DB Eloquent with() and get only specific column (Nested Eager Loading Specific Columns)

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

Answers (1)

Elbo Shindi Pangestu
Elbo Shindi Pangestu

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

Related Questions