如何创建唯一索引,它需要一组属性是唯一的?

How can I create unique index, that requires a set of attributes to be unique?

你好堆栈溢出

我遇到了 Laravel 的问题,我不确定如何解决它。

情况如下:

我得到了一个迁移,名称为 'adresses':

Schema::create('adresses', function (Blueprint $table) {
    $table->id();
    $table->string('adress'); //adress
    $table->integer('houseNumber'); //house number
    $table->string('houseNumberAddition')->nullable(); //house number addition
    $table->timestamps();
});

我想达到的目标: 我希望地址、houseNumber 和 houseNumberAddition 一起成为 1 个唯一值。

通常您会添加 unique() 函数,以使特定字段唯一。 但我希望将 address、houseNumber 和 houseNumberAddition 组合在一起,成为一个唯一值。

(因为houseNumber和houseNumberAddition会被多次使用,而address、houseNumber和houseNumberAddition的组合在我的数据库中只会存在一次。)

我希望有人有一些奇特的技巧来解决这个问题。

感谢您的帮助!

戴夫

您可以将 3 列组合在一个唯一索引中

$table->unique(['adress', 'houseNumber', 'houseNumberAddition']);