码迷,mamicode.com
首页 > 其他好文 > 详细

laravel 多对多 belonsToMany

时间:2015-09-15 00:12:51      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

  1. 建库,建model
    php artisan make:migration create_tags_table --create=tags
    php artisan make:model Tag

     

  2. 加字段
    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateTagsTable extends Migration
    {
    
        public function up()
        {
            Schema::create(‘tags‘, function (Blueprint $table) {
                $table->increments(‘id‘);
                $table->string(‘name‘);
                $table->timestamps();
            });
          //字母顺序,单数形式表名下划线结合定义中间表名
            Schema::create(‘article_tag‘, function (Blueprint $table) {
                $table->integer(‘tag_id‘)->unsigned()->index();
                $table->foreign(‘tag_id‘)->references(‘id‘)->on(‘tags‘)->onDelete(‘cascade‘);
                $table->integer(‘article_id‘)->unsigned()->index();
                $table->foreign(‘article_id‘)->references(‘id‘)->on(‘articles‘)->onDelete(‘cascade‘);
                $table->timestamps();
            });
        }
    
        public function down()
        {
            Schema::drop(‘tags‘);
            Schema::drop(‘article_tag‘);
        }
    }

     

  3. 添加关系
    //在Article模型中
        public function tag()
        {
            return $this->belongsToMany(‘App\Tag‘);
        }
    //在Tag中
        public function article()
        {
            return $this->belongsToMany(‘App\Article‘);
        }

     

  4. 调用
    $article->tag()->attach($id)
    $tag->article()->attach($id)

     

laravel 多对多 belonsToMany

标签:

原文地址:http://www.cnblogs.com/fenle/p/4808898.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!