use*_*986 97 database-schema laravel-4
如何在两列上设置唯一约束?
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);
Run Code Online (Sandbox Code Playgroud)
Col*_*mes 229
第二个参数是手动设置唯一索引的名称.使用数组作为第一个参数,可以跨多个列创建唯一键.
$table->unique(array('mytext', 'user_id'));
Run Code Online (Sandbox Code Playgroud)
或者(有点整洁)
$table->unique(['mytext', 'user_id']);
Run Code Online (Sandbox Code Playgroud)
Mal*_*med 17
如果您有一个包含一列的默认唯一索引,并且您将使用两列更改它,或者创建一个包含两列的新索引,则此脚本将为您执行此操作:
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');
});
}
Run Code Online (Sandbox Code Playgroud)
İsm*_*urt 15
只需你可以使用
$table->primary(['first', 'second']);
Run Code Online (Sandbox Code Playgroud)
参考: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']);
});
Run Code Online (Sandbox Code Playgroud)