更新现有列的数据并通过迁移复制数据

R0K*_*KET 6 laravel laravel-seeding laravel-migrations laravel-schema-builder

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

我有一张类似这样的桌子;

ID 物品 价格
1 项目一 100.00
2 项目二 200.00

现在我需要做的是,

  1. old_price向该表添加一个新列
  2. 将列中的值复制price到新添加的old_price
  3. 将列中的值乘以price5 并更新同一列

新表应该看起来像这样;

ID 物品 价格 旧价格
1 项目一 500.00 100.00
2 项目二 1000.00 200.00

是否有可能通过迁移或种子或其他东西来实现这一目标?

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

此外,old_price创建该列只是为了保留该列当前值的引用price。在此之后它不会更新,如果一切都按照新价格进行,则可能会在以后的更新中删除。所以我不需要使用任何模型事件来更新列。

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

boo*_*lse 11

Create a new migration.

Version 1. create automatically by command:

php artisan make:migration add_price_old_to_products_table
Run Code Online (Sandbox Code Playgroud)

Version 2. create manually something like this:

2021_08_18_163618_add_price_old_to_products_table.php

Manage the content by following the 3 steps in the code:

<?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');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

Run that migration for creating a new column:

php artisan migrate
Run Code Online (Sandbox Code Playgroud)