如何在两列上设置唯一约束?
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);
答案 0 :(得分:199)
第二个参数是手动设置唯一索引的名称。使用数组作为第一个参数,可以跨多个列创建唯一键。
$table->unique(array('mytext', 'user_id'));
或(有点整洁)
$table->unique(['mytext', 'user_id']);
答案 1 :(得分:14)
只需使用
即可$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']);
});
答案 2 :(得分:-1)
DB::statement("ALTER TABLE `project_majr_actvities`
ADD UNIQUE `unique_index`(`activity_sr_no`, `project_id`)");