重命名列名后如何在laravel中迁移而不丢失数据?

时间:2018-08-18 15:57:12

标签: laravel migration

场景:我创建了一个列名price,其中包含大量数据,现在我需要将该“价格”列名更改为oldPrice而不丢失其数据并使用迁移。 有什么办法请告诉我。谢谢

1 个答案:

答案 0 :(得分:2)

执行或撤消迁移中的任何更改。您必须编写新的迁移,这不会使您或您的队友丢失任何数据,并且您的应用程序也不会损坏。

要更改列,请使用以下内容:

进行迁移

php artisan make:migration change_price_to_old_price --table=table_name

并根据您的要求使用以下代码。

在up()函数中:

public function up(){
   Schema::table('table_name', function (Blueprint $table) {
       $table->renameColumn('old_name', 'new_name');
   });
}

在down()函数中只需撤消您在up()

中所做的操作
public function down(){

   Schema::table('table_name', function (Blueprint $table) {
       $table->renameColumn('new_name', 'old_name');
   });
}

推荐: 始终编​​写down迁移以撤消up函数中的操作。 php artisan migration:status ,以查看哪些迁移已运行,哪些仍在剩余。

点击 php artisan migration:并查看命令列表并了解它们