Skip to content
Advertisement

Laravel – query to join tables in Many to many relation

I have the below tables

posts
    - id
    - name

categories
    - id
    - name

category_post
    - post_id
    - category_id

Post.php

JavaScript

Category.php

JavaScript

A post may contain many categories.

I want to query all posts related to the categories of any given post in the least number of database queries.

For example, If a post belongs to three categories, I want to get all the posts related to that three categories. I could achieve this in 4 DB queries as below.

JavaScript

Any help would be highly appreciated to reduce DB queries or refactor the code in laravel way. Thanks

Advertisement

Answer

Your given example can be written like:

JavaScript

This is a single query but has 2 sub-queries within it. It generates something like:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement