534   Laravel PHP

posts与tags是多对多的关系,laravel实现也比较容易

1,首先新建三个表格posts,tags,以及posts_tags;
posts与tags表格存储基本信息,posts_tags存储两者的id,

        Schema::create('posts_tags', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->index();
            $table->integer('tag_id')->index();
            $table->timestamps();
        });

2,分别在posts与tags的模型添加以下方法:

post

    public function tags()
    {
        return $this->belongsToMany('App\Tags', 'posts_tags', 'post_id', 'tag_id'); //posts_tags是关系表名,post_id是post模型在关系表的key,tag_id是tag模型在关系表里的key
    }

tags

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

3,获取post的tag,以及获取tag的post


$tags= Post::find(1)->tags;

foreach ($tags as $tag) {
    //
}


$posts = Tags::find(1)->posts();

foreach($posts as $post){

}




Leave a Reply

Your email address will not be published. Required fields are marked *