雄辩的ORM(laravel):从与数据透视表关联的两个表中进行选择


eloquent ORM (laravel): select from two tables associated with pivot table

我的数据库中有树表(帖子标签Post_tag(数据透视表)):

  1. 帖子(ID,内容,标题,...)
  2. 标签(编号,tag_name)
  3. post_tag(同上,post_id,tag_id)

现在我的问题是关于如何选择与帖子具有相同标签的所有帖子,例如:选择与帖子 1 具有相似标签的所有帖子。我已经创建了帖子和标签表之间的关系:在帖子表中:

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

在标签表中:

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

我尝试过:

    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'));
        }
    }

像这样

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