laravel - 如何将唯一约束添加到 laravel 中现有的 foreignId 列?

标签 laravel migration unique

我在数据库中有一个包含数据的现有表,我想向其中的 customer_id 列添加唯一约束。

我尝试执行 $table->foreignId('customer_id)->unique()->change()。但这似乎不起作用。这同样适用于任何非外部字段,如字符串和整数。

错误:

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'customer_id' (SQL: alter table `partner_preferences` add `customer_id` bigint unsigned not  

空)

最佳答案

foreignId()本质上是创建一个新列,在您的情况下该列已经存在。

The foreignId method is an alias of the unsignedBigInteger method:

laravel - difference between foreignId() and unsignedBigInteger()

请试试这个:

Unique constraint

    public function up()
    {
        // Change the 'table name' according to your needs.
        Schema::table("employees", function (Blueprint $table) {

            $table->unique('customer_id');
        });
    }

警告:确保您应用此约束的列实际上唯一。 (必须具有唯一数据。)

否则,将抛出错误(SQLSTATE[23000]:违反完整性约束:1062 Duplicate entry '1' for key 'XXXX_customer_id_unique')。

关于laravel - 如何将唯一约束添加到 laravel 中现有的 foreignId 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68087622/

相关文章:

laravel - Uncaught ReferenceError : Vue is not defined when using laravel-mix webpack

javascript - 使用 jQuery AJAX 将数据库默认值添加到下拉列表

mysql - 迁移 Rails 基表,表名称包含 *

ruby-on-rails - rails 数据库 :migrate relation does not exist

php - Laravel Dusk - 调用数组上的成员函数 click()

ruby-on-rails - Rails 迁移 : Check Existence and Keep Going?

javascript - 如何检查对象数组是否具有重复的属性值?

Rstudio 和 R 终端给出不同的输出

python - 与 nan 结成独特的情侣

php - laravel 组件类被忽略