如何在两列上设置唯一约束?
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);
id
的事实,给框架带来了边缘的业余感觉。我在吐槽吗? :-(
第二个参数是手动设置唯一索引的名称。使用数组作为第一个参数来创建跨多列的唯一键。
$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']);
});
->unique()
。
->unique()
在这个特定问题中更合适,因为 'mytext'
可能会像任何 VARCHAR
或 TEXT
列一样导致错误的键。 ->primary([])
非常适合确保整数(例如枢轴外键)的唯一性。
如果您有一个包含一列的默认唯一索引,并且您将使用两列更改它,或者创建一个包含两列的新索引,则此脚本将为您执行此操作:
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');
});
}
DB::statement("ALTER TABLE `project_majr_actvities`
ADD UNIQUE `unique_index`(`activity_sr_no`, `project_id`)");
不定期副业成功案例分享
array()
+1。因为我尝试不使用数组但它不起作用。我可以在通过 Schema builder 运行复合键时给出约束名称吗?table_column1_column2...n_unique
。删除唯一约束将引用$table->dropUnique('table_column1_column2...n_unique');
中的唯一约束unique()
的相同数组传递给dropUnique()
以保证约束/索引名称相同。