架构生成器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);
130219 次浏览

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

$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->primary(['post_id', 'tag_id']);
});
DB::statement("ALTER TABLE `project_majr_actvities`
ADD UNIQUE `unique_index`(`activity_sr_no`, `project_id`)");

如果您有一个包含一列的默认唯一索引,并且您将使用两列来更改它,或者创建一个包含两列的新索引,则此脚本将为您执行此操作:

public function up()
{
Schema::table('user_plans', function (Blueprint $table) {
$table->unique(["email", "plan_id"], 'user_plan_unique');
});
}


public function down()
{
Schema::table('user_plans', function (Blueprint $table) {
$table->dropUnique('user_plan_unique');
});
}