【问题标题】:How to add extra columns to an existing migration table without lossing data in laravel?如何在现有迁移表中添加额外的列而不丢失 laravel 中的数据?
【发布时间】:2021-10-15 19:25:39
【问题描述】:

我有一个负责存储详细信息的迁移表,在我的数据库中它包含一些数据,现在我想在现有表中添加一些两列而不丢失数据库中的任何数据(这些应该反映在我的数据库中也不会影响我数据库中的任何数据)。我想在我现有的表中添加这些列$table->string('country'); $table->string('station'); 如何实现这件事,请指导我在我现有的表中添加列..

migration table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('passport_table', function (Blueprint $table) {
            
            $table->id();
            $table->string('name');
            $table->string('price');
            $table->integer('rating');
            $table->longText('image');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('user_table');
            $table->timestamps();
            //$table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('passport_table');
    }
}

【问题讨论】:

标签: laravel laravel-migrations


【解决方案1】:

您创建一个新的迁移php artisan make:migration add_extra_fields_passport_table,迁移应该如下所示。

public function up(): void
{
    Schema::table('passport_table', function (Blueprint $table) {
        $table->string('country')->after('image');
        $table->string('station')->after('country'); 
    });
}

public function down(): void
{
    Schema::table('passport_table', function (Blueprint $table) {
        $table->dropColumn('country');
        $table->dropColumn('station');
    });
}

您使用迁移来确保所有数据库在本地、暂存、生产等方面保持同步。如果您重写迁移,如果执行了某些迁移,它们将不会同步。我使用after() 方法来确保在image 列之后的表格中正确放置。

如果您只在本地单独开发并且没有发布任何内容,您可以更改原始迁移。然后,您必须在迁移表中删除与您的文件对应的迁移行并清理表结构以避免重新运行迁移时出错。或者,可以回滚迁移,这是另一种方法。然后你可以运行 php artisan migrate ,它会再次重新运行相同的代码。但建议只创建一个新的迁移,这样更容易。

【讨论】:

  • 是的,这就是你想要的?它不会改变任何已经存在的东西,但会添加新的列。类似于 ALTER TABLE passport_table ADD country varchar(255);
  • 是的,这就是我想要的,谢谢
猜你喜欢
  • 2018-05-20
  • 2016-08-11
  • 2020-03-12
  • 2020-02-13
  • 2016-07-09
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 2013-05-23
相关资源
最近更新 更多