如何解决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
下。这就是为什么您的代码无法正常工作的原因。
在不丢失数据的情况下,您可能必须:
-
在特定位置创建一个新的:
$table->string('xyx')->after('qwe');
-
将数据从旧数据复制到新数据。
-
删除旧列。
尝试执行以下步骤,希望您缺少一些看起来不错的代码。
删除现有迁移并添加新迁移
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')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。