0

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?

Radical_Activity
  • 2,618
  • 10
  • 38
  • 70
  • https://github.com/laravel/framework/issues/6161 – STA Oct 27 '20 at 11:52
  • 2
    Laravel will always make separate queries if you use `with` because this is most efficient. You could do something like `Comments::where('post_id', $post_id)->join('posts', 'posts.id', 'comments.post_id')->get()` to make it 1 query. But please notice that 1 query is not per definition better than multiple queries. – Techno Oct 27 '20 at 12:12
  • @RobBiermann Ah I see, I thought one query is going to have better performance. It makes sense. Thanks for pointing this out, I'll keep it in mind! – Radical_Activity Oct 27 '20 at 12:16

0 Answers0