A bug with renaming existing column in Laravel migrations

本秂侑毒 提交于 2020-01-14 13:10:46

问题


I added a new migration to rename an old column. Everything seems correct in this code, for me:

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

But then I faced an error:

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. `

Could you help me to fix this?


回答1:


First drop koreign key on up method.

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

Then add foreign key again on down method.

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



回答2:


I've encountered this too - it makes no sense, because when I use my standard SQL client to rename the same field ... it works. But it just doesn't work as a migration script. Thus, I ended up running the RENAME inside a DB::statement and that worked for me:

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

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

    }


来源:https://stackoverflow.com/questions/49667032/a-bug-with-renaming-existing-column-in-laravel-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!