Laravel 4 架构生成器laravel迁移在两列上是唯一的

Laravel 4 架构生成器laravel迁移在两列上是唯一的,laravel-4,database-schema,Laravel 4,Database Schema,如何在两列上设置唯一的约束 class MyModel extends Migration { public function up() { Schema::create('storage_trackers', function(Blueprint $table) { $table->increments('id'); $table->string('mytext'); $table->unsignedInteger('use

如何在两列上设置唯一的约束

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);

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

$table->unique(array('mytext', 'user_id'));
或者(稍微整洁一点)

简单地说,你可以使用

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

例如:

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

+谢谢你…不知道我怎么会在文档中漏掉它。我一定是瞎了眼:PI也不知何故忽略了第二个参数是手动命名索引的事实,我有一个自动生成的索引名太长了。谢谢你,伙计+1+1表示
array()
。因为我在没有阵列的情况下尝试了,但它不起作用。我可以在通过Schema builder运行复合键时给出约束名称吗?是的,这是第二个参数。如果有人不确定,生成的索引名称的格式为
table_column1_column2…n_unique
。删除唯一约束将引用
$table->dropUnique('table_column1_column2…n_unique')中的约束这并不能保证唯一性,它只是添加了一个复合索引。通常,您不希望在同一篇文章上两次使用同一标记,因此对于这种用例,最好使用
->unique()
@Fx32,这确实保证了唯一性,因为它创建了一个复合主键(索引)。但是,我仍然同意
->unique()
在这个特定问题中更合适,因为
'mytext'
可能会像任何
VARCHAR
TEXT
列一样成为一个坏键
->primary([])
对于确保整数(如pivot外键)的唯一性非常有用。另外请注意,Laravel开发人员通常不喜欢复合主键,并且雄辩者不支持复合主键-请参阅,此级别的详细信息的可能重复令人遗憾地从中丢失。顺便提一下是很容易的。像这样的细节以及(例如)框架似乎总是假设每个表都有自动递增的
id
,这一事实给了框架一种边缘的业余感觉。我在咆哮吗-(口头解释将有助于补充你的答案这是核选项
    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`)");