Laravel - 迁移以在现有表列上添加可为空的属性

问题描述 投票:0回答:1

我已经开始在 Laravel 10 上编写小型个人项目。我遇到的问题如下:

  1. 我有用户表,其中有外部 UUID - role_id。
  2. 我想向该列添加可空值而不删除表。
  3. 我创建了新的迁移来进行更改。
  4. 安装了doctrine/dbal包以便能够(理论上)更改列。
  5. 我在迁移中的代码是:
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignUuid('role_id')->nullable()->constrained('roles')->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->foreignUuid('role_id')->nullable(false)->constrained('roles')->change();
        });
    }

但是当我运行 php artisan migrate 时,出现以下错误 - SQLSTATE[42S21]: 列已存在: 1060 重复列名 'role_id' (连接: mysql, SQL: alter table users add role_id char(36) null)。

非常感谢您提供有关如何正确更改该列的任何建议。

php mysql laravel database-migration
1个回答
2
投票

您可以尝试以下方法:

      Schema::table('users', function (Blueprint $table) {
            $table->char('role_id', 36)->nullable()->constrained('roles')->change();
        });

或者可能使用原始 sql 语句,例如:

    DB::statement('ALTER TABLE users MODIFY role_id CHAR(36) NULL');
    DB::statement('ALTER TABLE users ADD CONSTRAINT fk_users_role_id FOREIGN KEY (role_id) REFERENCES roles (id)');

© www.soinside.com 2019 - 2024. All rights reserved.