更新现有列的数据并使用迁移复制数据

Updating the data of an existing column and copying data with migrations

是否可以添加一个新列,将一些数据复制到这个新列并使用 Laravel 迁移更新另一列中的数据?

我有一个 table 像这样的东西;

id item price
1 ItemOne 100.00
2 ItemTwo 200.00

现在我需要做的是,

  1. 向此 table
  2. 添加一个新列 old_price
  3. price列中的值复制到新添加的old_price
  4. price 列中的值乘以 5 并更新同一列

新的 table 应该是这样的;

id item price old_price
1 ItemOne 500.00 100.00
2 ItemTwo 1000.00 200.00

是否可以通过迁移或种子之类的方式实现这一点?

此更改需要在已投入生产的应用程序上完成,因此删除并重新创建 tables 对我来说不是一个选项。

还创建了 old_price 列,只是为了保留对 price 列当前值的引用。之后 将不会 更新,如果新价格一切正常,它可能会在以后的更新中被删除。所以之后我不需要使用任何模型事件来更新列。

非常感谢您在这方面给我的任何帮助。谢谢。

创建一个新的迁移。

版本1.通过命令自动创建:

php artisan make:migration add_price_old_to_products_table

版本 2. 像这样手动创建:

2021_08_18_163618_add_price_old_to_products_table.php

按照代码中的 3 个步骤管理内容:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class AddPriceOldToProductsTable extends Migration
{
    public function up()
    {
        // 1. creating a new column
        Schema::table('products', function (Blueprint $table) {
            // this is just an example, you can change this
            // NOTE: make sure that the type is the same as "price" column
            // for avoiding type conflicts
            $table->decimal('price_old', 10, 2)->nullable();
        });

        // 2. copying the existing column values into new one
        DB::statement("UPDATE products SET price_old = price");

        // 3. update the old/existing column
        // CHANGE YOUR "price" COLUMN HERE...
    }

    public function down()
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn('price_old');
        });
    }
}

运行 用于创建新列的迁移:

php artisan migrate