【发布时间】:2020-02-12 06:26:16
【问题描述】:
我有一个 Laravel 应用程序,它有一个 users 表,大约有 5000 条记录。该表有一列name,需要替换为first_name 和last_name。
通过一个简单的迁移脚本,我更新了架构并编写了一个简单的工匠命令将名称拆分为第一个和最后一个并在数据库中恢复。
现在通过回滚迁移,我丢失了 last_name 列以及数据。我正在寻找的是如何在up 方法执行之后和down 方法之前运行一些东西。
实现这一目标的最合适方法是什么?
迁移:
class ChangeColumnsInUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('name', 'first_name');
$table->string('last_name')->after('name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('first_name', 'name');
$table->dropColumn('last_name');
});
}
}
【问题讨论】:
-
对于这样的用例,我根本不建议接触迁移,在 User 模型上有两个访问器来表示
first_name和last_name中的name会容易得多
标签: php mysql laravel migration