简体   繁体   English

如何使用 Laravel 迁移从列中删除唯一约束?

[英]How to remove unique constraint from a column using Laravel migrations?

I have to remove a unique constraint from an email column using Laravel migrations.我必须使用 Laravel 迁移从电子邮件列中删除唯一约束。 Here is my code:这是我的代码:

class AlterEmailToUsers extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('email')->unique(false)->nullable()->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function (Blueprint $table) {
       $table->string('email')->nullable(false)->unique()->change();
    });
}

} }

But when I run php artisan migrate , I get the following error:但是当我运行php artisan migrate时,出现以下错误:

SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_email_unique' (SQL: alter table `users` add unique `users_email_unique`(`email`)) SQLSTATE[42000]:语法错误或访问冲突:1061 Duplicate key name 'users_email_unique'(SQL:alter table `users` add unique `users_email_unique`(`email`))
 public function up()
 {
   Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique(false)->nullable()->change();
   });
  }

change to改成

$table->dropUnique('users_email_unique');

The provided solution works just fine but just one small tip here:提供的解决方案工作得很好,但这里只有一个小提示:
You can pass an array with the name of the column like so:您可以传递一个带有列名称的数组,如下所示:

$table->dropUnique(['email']); 

in this case, Laravel will generate the index name automatically based on its conventions在这种情况下,Laravel 将根据其约定自动生成索引名称

I went through this problem, when using softDeletes on all tables, which caused this need, for new users, once deleted logically.我在所有表上使用softDeletes时遇到了这个问题,这导致了新用户的这种需求,一旦被逻辑删除。

So, I created a migration by setting the users table (--table=users) and placed the removal of the constraint, but then I redid the action for possible new inclusion needs.因此,我通过设置 users 表 (--table=users) 创建了迁移并删除了约束,但随后我重新执行了操作以满足可能的新包含需求。

But I used it only because of the softDeletes, be careful with your business rules.但我只是因为softDeletes而使用它,请注意您的业务规则。 I keep validating existence in request rules.我不断验证请求规则中的存在。

The code is as follows (up and down methods only):代码如下(仅限 up 和 down 方法):

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropUnique(['email']);
    });
}


public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->unique(['email']);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM