【问题标题】:How to add unique constraint to an existing foreignId column in laravel?如何在 laravel 中为现有的 foreignId 列添加唯一约束?
【发布时间】:2021-06-22 16:43:06
【问题描述】:

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

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

错误:

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

空)

【问题讨论】:

    标签: laravel migration unique


    【解决方案1】:

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

    foreignId 方法是unsignedBigInteger 方法的别名:

    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]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'XXXX_customer_id_unique')。

    【讨论】:

    • 所以默认情况下foreignId 不是unique 正确吗?
    • @steven7mwesigwa 非常感谢,成功了!
    • 当列中已经存在非唯一数据时,是否有任何方法使列唯一?还是唯一的方法是先截断表格?
    • @Saurabh ,如果您创建唯一键,则不能有重复项。即使使用原始 SQL 查询 (ALTER TABLE table_name ADD UNIQUE unique_constraint_name (unique_columns)) 也是不可能的。如果您正在处理生产数据,最好的办法是首先删除重复项。对于测试数据,可以先截断表格。
    • @Saurabh 一种安全的方法是复制该列。即重命名旧的,用原始名称创建一个新的,使其唯一并且可以为空,然后编写一个方法将数据从旧列复制到新列中。但是你的方法应该只保留第一次出现的值,并将后续出现的值保留为 NULL。
    猜你喜欢
    • 2013-05-11
    • 2013-03-08
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多