Laravel的重命名列迁移更改了列的位置

问题描述

我正在执行的迁移文件

Schema::table('table_xyz',function (Blueprint $table) {
    $table->renameColumn('col_old_name','col_new_name');
});

运行此迁移将使用新的列名更新table_xyz,但还会更改列在数据库中的位置(将列放在最后)

为避免我这样做:

Schema::table('table_xyz','col_new_name')
           ->after('col_to_be_after')
});

这也没有得到想要的结果。

我想念什么?

解决方法

如果要保留数据,这是一种处理方法:

public function up()
{
    //Give the moving column a temporary name:
    Schema::table('table_xyz',function($table)
    {
        $table->renameColumn('col_new_name','col_old_name');
    });

    //Add a new column with the regular name:
    Schema::table('table_xyz',function(Blueprint $table)
    {
        $table->string('col_new_name')->after('col_to_be_after');
    });

    //Copy the data across to the new column:
    DB::table('table_xyz')->update([
        'col_new_name' => DB::raw('col_old_name')   
    ]);

    //Remove the old column:
    Schema::table('table_xyz',function(Blueprint $table)
    {
        $table->dropColumn('col_old_name');
    });
}
,

您不能这样做

    $table->renameColumn('col_old_name','col_new_name')
           ->after('col_to_be_after')

renameColumn()返回Illuminate\Support\Fluent,但是->after()Illuminate\Database\Schema\ColumnDefinition下。这就是为什么您的代码无法正常工作的原因。

在不丢失数据的情况下,您可能必须:

  1. 在特定位置创建一个新的:$table->string('xyx')->after('qwe');

  2. 将数据从旧数据复制到新数据。

  3. 删除旧列。

,

尝试执行以下步骤,希望您缺少一些看起来不错的代码。

删除现有迁移并添加新迁移

 rm database/migrations/your-migration-file`
 
 php artisan make:migration rename_col_old_name_table_xyz_table --table=table_xyz

up()down()中添加以下代码

public function up()
{
    Schema::table('table_xyz',function (Blueprint $table) {
        $table->renameColumn('col_old_name','col_new_name');
    });
}
And down() function with this,public function down()
{
    Schema::table('table_xyz',function (Blueprint $table) {
        $table->renameColumn('col_new_name','col_old_name');
    });
}

有关详细文档,请检查Renaming columns in migrations

由于您正在重命名列,因此不应在末尾添加,因此我认为您不需要添加->after('col_to_be_after')