创建一个新的迁移。
版本 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