dongyuan9149
dongyuan9149
2017-06-15 03:08

Laravel,如何在使用belongsToMany时过滤行?

已采纳

I'm confused about the Laravel API and its many to many relationship model.

There are the following tables:

posts tags post_tag

And I want to find posts which have tagId = 123

Is there simple source code similar to the following?

$posts= Post::find()->pivot->tag(123);

Thanks.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doudao2407 doudao2407 4年前

    You should specify the method in Tag model:

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

    Then you can find posts which have tagId = 123

    $posts = Tag::find(123)->posts();
    
    点赞 评论 复制链接分享

相关推荐