如何向 Laravel 中现有的foreignId 列添加唯一约束?

Kat*_*des 8 migration unique laravel

我在数据库中有一个包含数据的现有表,我想向其中的 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  
Run Code Online (Sandbox Code Playgroud)

无效的)

ste*_*gwa 12

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

foreignId方法是该方法的别名unsignedBigInteger

laravel -foreignId() 和 unsignedBigInteger() 之间的区别

请尝试这个:

唯一约束

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

            $table->unique('customer_id');
        });
    }
Run Code Online (Sandbox Code Playgroud)

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

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'XXXX_customer_id_unique'否则,将抛出错误 ( )。