zoukankan      html  css  js  c++  java
  • laravel 多对多 belonsToMany

    1. 建库,建model
      php artisan make:migration create_tags_table --create=tags
      php artisan make:model Tag
    2. 加字段
      <?php
      
      use IlluminateDatabaseSchemaBlueprint;
      use IlluminateDatabaseMigrationsMigration;
      
      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 tags()
          {
              return $this->belongsToMany('AppTag');
          }
      //在Tag中
          public function articles()
          {
              return $this->belongsToMany('AppArticle');
          }
    4. 调用
      $article->tags()->attach($id)
      $tag->articles()->attach($id)
    5. 视图多选框
          <div class='form-group'>    
              {!! Form::label('tags', 'Tags') !!}
              {!! Form::select('tags[]',$tags, null, ['class'=>'form-control','multiple']) !!}
          </div>    
    6. create ,  store
          public function create()
          {
              $tags = AppTag::lists('name','id');
      
              return view('articles.create', compact('tags'));
          }
      
          public function store(ArticleRequest $request)
          {
              
              $article = Auth::user()->articles()->create($request->all());
      
              $article->tags()->attach($request->tags);
      
              flash()->success('Your article has been created!');
      
              return  redirect('articles');
      
          }
  • 相关阅读:
    hdu 5916
    hdu 5918
    hdu 5914 Triangle
    hdu 5912Fraction
    遗传算法初学习
    hdu 5873 Football Games
    JAVA 定时器的三种方法
    java反射对实体类取值和赋值,可以写成通过实体类获取其他元素的数据,很方便哦~~~
    Eclipse设置Tab键缩进4个空格的步骤,也就是按一下Tab键输出四个空格
    Nginx 相关介绍(Nginx是什么?能干嘛?个人觉得写得比较好的文章,转载过来)
  • 原文地址:https://www.cnblogs.com/fenle/p/4808898.html
Copyright © 2011-2022 走看看