【问题标题】:Run specific code on execution of up and down methods of a migration in laravel在 laravel 中执行迁移的 up 和 down 方法时运行特定代码
【发布时间】:2020-02-12 06:26:16
【问题描述】:

我有一个 Laravel 应用程序,它有一个 users 表,大约有 5000 条记录。该表有一列name,需要替换为first_namelast_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_namelast_name 中的 name 会容易得多

标签: php mysql laravel migration


【解决方案1】:

您是否考虑将“简单脚本”添加到迁移本身的up()down() 函数中?像这样的东西行得通吗?

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('first_name');
            $table->string('last_name');
        });

        // Fill the first_name and last_name based on the name column

        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('name');
        });
    }

down() 方法也可以这样做,除了相反。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多