如何在laravel 5.5中以多对多关系获取特定类别的记录

时间:2018-07-15 05:27:29

标签: php laravel-5.5

我有三个表1个帖子,2个类别和3个category_post,我已经做了所有必要的事情,现在的问题是,如何在控制器中获取某个类别的特定记录,例如我想检索所有属于动物类别的帖子

提前感谢

1 个答案:

答案 0 :(得分:0)

您将需要定义它们之间的关系:

class Posts extends Model {

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

}
class Category extends Model {

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

}

您还需要一个post_category数据透视表,其中包含两列: post_id category_id

Post::with('category')->get(); // will return all posts and their categories
相关问题