Laravel迁移中重命名现有列的错误

4

我添加了一个新的迁移来重命名一个旧列。这段代码对我来说看起来一切都正确:

public function up()
{
   Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('reporter_id', 'created_by');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('created_by', 'reporter_id');
    });
}

但是我遇到了一个错误:
In Connection.php line 664: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. (SQL: ALTER TABLE reports CHANGE reporter_id created_b    y INT NOT NULL)                                                                                                                                                                                                          
In PDOStatement.php line 140: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE.
In PDOStatement.php line 138: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. `

你能帮我修复这个问题吗?


这并不是 Laravel 的 bug 或者相关问题。这是数据库服务器告诉您,当其他表将该列作为外键时,您无法重命名列。您需要从其他表中删除该列现有的外键,重命名该列,然后再在其他表中创建外键以指向重命名后的列。 - M. Eriksson
你遇到这个问题是因为你正在更新其他表中使用的关键字...首先请检查这一点。 - Muhammad Rizwan
你指的是哪个表格里的 reporter_id? - Sohel0415
2个回答

1

up方法中首先删除koreign key

public function up()
{
  Schema::table('reports', function (Blueprint $table) {
     $table->dropForeign('reports_reporter_id_foreign');
     $table->renameColumn('reporter_id', 'created_by');
  });
}

然后在 down 方法中再次添加 foreign key。保留html,不做解释。
public function down()
{
    Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('created_by', 'reporter_id');
        $table->foreign('reporter_id')->references('id')->on('your_related_table')->onDelete('cascade');
    });
}

1

我也遇到了这个问题 - 这没有意义,因为当我使用我的标准SQL客户端来重命名相同的字段时...它可以工作。但是作为迁移脚本,它就是不起作用。因此,我最终在 DB::statement 中运行 RENAME 命令,这对我有效:

     /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        DB::statement("ALTER TABLE `mydb`.`mytable`   
          CHANGE `currentfieldname` `newfieldname` 
          INT(10) UNSIGNED NOT NULL;");

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接