I'm using Laravel 8. I would like to access data from Table C to Table A, through Table B with only 1 query.
Let's say I have the following tables:
A) Pages
B) Posts
C) Comments
How can I get the Page of a Comment if I only have the Post ID in the Comments table with 1 Query?
This is what I currently have:
Comments Model:
public function post()
{
return $this->belongsTo('App\Models\Comments', 'post_id');
}
Posts Model:
public function page()
{
return $this->belongsTo('App\Models\Pages', 'page_id');
}
...and I'm trying to access the Page
from Comments
like this:
Comments::with('post.page')->get();
While this is working fine, Laravel is executing 3 queries here instead of the 1 that I would need. What am I missing here?