Shehzad
Shehzad

Reputation: 347

Laravel Retrieving Specific fields from nested Relationships

I have some nested relationships, Following are my models: Post, Thread and BookPage. and their relationships:

Post

class Post extends Model
{

    public function thread(){
        return $this->belongsTo('App\Thread');
    }

}

Thread

class Thread extends Model
{

    public function bookPage(){
        return $this->belongsTo('App\BookPage');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }

}

BookPage

class BookPage extends Model
{

    public function threads(){
        return $this->hasMany(App\Threads);
    }

}

now i wanted to get posts with the bookpages and threads but only some fields let say only thread name and bookpage title

I have read about retrieving relationships and i am doing exactly like explained in the docs but here is my problem :

When i am retrieving posts with relations without specifying fields i am getting results fine:

Query:

$posts = Post::with('thread.bookpage:id,title)->get();
return $posts->toArray();

Result:

Result

but when i specify fields for both i.e fields for bookpage and also fields for thread i am getting bookpage as null. I am able to get specific fields for one relation only either for bookpage or either for thread. I have tried to query in the following ways:

$posts = Post::with('thread.bookpage:id, ...')->get();
//thread:all fields, bookpage:specified fields

$posts = Post::with('thread.bookpage', 'thread:id, ...')->get();
//thread:specified fields, bookpage:bull

Here is the result if i tried to specify fields for both: enter image description here

so how can i get the specific fields only from the relation and its nested relation ?

Upvotes: 0

Views: 1210

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You have to select all the foreign keys (here: thread.book_page_id) that Laravel requires to match the eager loading results to their parents:

$posts = Post::with('thread:id,book_page_id', 'thread.bookpage:id,title')->get();

Upvotes: 4

Related Questions