Laravel – query to join tables in Many to many relation

  laravel, mysql, php, sql

I have the below tables

1.posts : id | name

2.categories : id | name

3.category_post :post_id | category_id

My Models contains

1.Post.php

public function Category() { return $this->belongsToMany(Category::class); }

2.Category.php

public function posts() { return $this->belongsToMany(Post::class); }

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.

$post = Post::find(1);

$categoryIds = ($post->category()->pluck('id'));

$postIds = DB::table('category_post')->whereIn('category_id',$categoryIds)->pluck('post_id')->unique();

$relatedPosts =DB::table('posts')->whereIn('id', $postIds)->get();

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

Source: Ask PHP

LEAVE A COMMENT