如何使用 laravel 5 迁移在表中添加列而不丢失其数据?

2022-01-23 00:00:00 postgresql migration php laravel-5.2

我有一个现有的数据库表,我想在其上添加列.但是,当我运行 php artisan migrate 命令时,它没有说明要迁移.但是我已经添加了一个用于添加表列的架构.我已经阅读了一些文章和链接,我应该在添加新列之前首先运行 php artisan migrate:refresh.问题是,它会删除我表中的现有数据.有什么方法可以在不删除数据的情况下执行迁移并成功在表中添加列?请帮我解决一下这个.非常感谢.这是我的迁移代码.

I have an existing database table and I want to add column on it. However, as I run the php artisan migrate command, it says nothing to migrate. But I already add a Schema for adding table columns. I have read some articles and links that I should run the php artisan migrate:refresh first before the new columns to be added.The problem is, it will erase my existing data in my table. Is there any way I could perform the migration and successfully add columns in my table without deleting my data? Please help me with this. Thanks a lot. Here is my migration code.

public function up()
{
    //
    Schema::create('purchase_orders', function(Blueprint $table){

        $table->increments('id');
        $table->string('po_code');
        $table->text('purchase_orders');
        $table->float('freight_charge');
        $table->float('overall_total');
        $table->timestamps();

    });

    Schema::table('purchase_orders', function(Blueprint $table){
        $table->string('shipped_via');
        $table->string('terms');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('purchase_orders');
}

我想在我的 purchase_orders 表中添加列 shipped_viaterms.

I want to add column shipped_via and terms in my purchase_orders table.

推荐答案

使用以下命令修改现有表

Use below command to modify the existing table

php artisan make:migration add_shipped_via_and_terms_colums_to_purchase_orders_table --table=purchase_orders

使用 --create 来创建新表,使用 --table 来修改现有表.

use --create for creating the new table and --table for modifying the existing table.

现在将创建一个新的迁移文件.在此文件的 up() 函数中添加这些行

Now a new migration file will be created. Inside the up() function in this file add these line

Schema::table('purchase_orders', function(Blueprint $table){
    $table->string('shipped_via');
    $table->string('terms');
});

然后运行php artisan migrate

相关文章