1
votes

I have tree tables in my database (Posts Tags Post_tag(pivot table)):

  1. Posts(id,content,title,...)
  2. Tags(id,tag_name)
  3. post_tag(id,post_id,tag_id)

Now my problem is about how can I select all posts with same tags to an post for example: select all posts that have similar tags as post 1. I have create the relationships between the posts and tags tables: In posts table:

    public function tags(){
    return $this->belongsToMany('App\Tag');}

In tags table:

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

What i tried:

    public function similar_tags($id)
    {
        $post = \App\Post::find($id);
        $all_posts = \App\Post::where('id','<>',$id)->where('catg_id','=',$post->catg_id);
        $result=array();
        if(count($post->tags)){
            foreach ($post->tags as $tag) {
                $all_posts = \App\Post::with('tags')->where('id','=',$id)->get();
                foreach ($all_posts as $post) {
                    $result[]=$post->post_id;
                }
            }
            return view('home',compact('result'));
;
        }else{
            $fa=0;
            return view('home',compact('fa'));
        }
    }
1
do you mean "get post with multiple tags" ? - Drudge Rajen
@Drudge get posts that have same tags not necessary all tags did you get it ? - S4L4H
yeah, but can you post the code that you have tried ?? - Drudge Rajen

1 Answers

0
votes

Something like this :

  $posts = Post::whereHas('tags', function($q) use ($tags)
{
    $q->whereIn('id', $tags);//get $tags first .
})->get();