繁体   English   中英

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

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

我必须使用 Laravel 迁移从电子邮件列中删除唯一约束。 这是我的代码:

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();
    });
}

}

但是当我运行php artisan migrate时,出现以下错误:

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();
   });
  }

改成

$table->dropUnique('users_email_unique');

提供的解决方案工作得很好,但这里只有一个小提示:
您可以传递一个带有列名称的数组,如下所示:

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

在这种情况下,Laravel 将根据其约定自动生成索引名称

我在所有表上使用softDeletes时遇到了这个问题,这导致了新用户的这种需求,一旦被逻辑删除。

因此,我通过设置 users 表 (--table=users) 创建了迁移并删除了约束,但随后我重新执行了操作以满足可能的新包含需求。

但我只是因为softDeletes而使用它,请注意您的业务规则。 我不断验证请求规则中的存在。

代码如下(仅限 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