架构生成器laravel迁移在两列上是独一无二的

我如何设置两列的唯一约束?

class MyModel extends Migration { public function up() { Schema::create('storage_trackers', function(Blueprint $table) { $table->increments('id'); $table->string('mytext'); $table->unsignedInteger('user_id'); $table->engine = 'InnoDB'; $table->unique('mytext', 'user_id'); }); } } MyMode::create(array('mytext' => 'test', 'user_id' => 1); // this fails?? MyMode::create(array('mytext' => 'test', 'user_id' => 2); 

第二个参数是手动设置唯一索引的名称。 使用一个数组作为第一个参数来跨多个列创build一个唯一的键。

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

或(一点点整洁)

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

只要你可以使用

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

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

举个例子:

  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']); });