schema builder laravel migrations unique on two columns

前端 未结 3 1606
离开以前
离开以前 2020-12-23 08:47

How can I set a unique constraints on two columns?

class MyModel extends Migration {
  public function up()
  {
    Schema::create(\'storage_trackers\', fun         


        
相关标签:
3条回答
  • 2020-12-23 09:09
    DB::statement("ALTER TABLE `project_majr_actvities`
                   ADD UNIQUE `unique_index`(`activity_sr_no`, `project_id`)");
    
    0 讨论(0)
  • 2020-12-23 09:17

    The second param is to manually set the name of the unique index. Use an array as the first param to create a unique key across multiple columns.

    $table->unique(array('mytext', 'user_id'));
    

    or (a little neater)

    $table->unique(['mytext', 'user_id']);
    
    0 讨论(0)
  • 2020-12-23 09:18

    Simply you can use

    $table->primary(['first', 'second']);
    

    Reference: http://laravel.com/docs/master/migrations#creating-indexes

    As an example:

        Schema::create('posts_tags', function (Blueprint $table) {
    
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
    
            $table->foreign('post_id')->references('id')->on('posts');
            $table->foreign('tag_id')->references('id')->on('tags');
    
            $table->timestamps();
            $table->softDeletes();
    
            $table->primary(['post_id', 'tag_id']);
        });
    
    0 讨论(0)
提交回复
热议问题