【问题标题】:How to change data type and add column with migration without losing data? (laravel 5.3)如何在不丢失数据的情况下更改数据类型并添加带有迁移的列? (laravel 5.3)
【发布时间】:2016-12-19 13:29:20
【问题描述】:

我的迁移是这样的:

public function up()
{
    Schema::create('tests', function (Blueprint $table) {
        $table->increments('id_test');
        $table->string('name', 50);
        $table->timestamps();
        $table->softDeletes();
    });
}

public function down()
{
    Schema::drop('tests');
}

我想更改数据类型并在表测试中添加列。然后更新数据库中的表。我这样编辑:

public function up()
{
    Schema::create('tests', function (Blueprint $table) {
        $table->increments('id');
        $table->string('id_test', 18);
        $table->string('name', 50);
        $table->timestamps();
        $table->softDeletes();
    });
}

public function down()
{
    Schema::drop('tests');
}

然后我运行:php artisan migrate:refresh

我在数据库中丢失了数据

有没有人可以帮助我?

【问题讨论】:

  • 简单:创建一个 new 迁移。不要编辑旧的。在up() 方法中添加新列,并在down() 方法中删除它。然后只需 php artisan migrate 运行更改。 php artisan migrate:rollback 扭转它。
  • 您可以通过reading the very thorough documentation了解更多关于迁移的信息

标签: php mysql laravel laravel-5.3


【解决方案1】:

使用以下命令创建一个新的迁移文件:

php artisan make:migration name_of_your_file

而且它的功能应该是这样的

    public function up()
        {
            Schema::table('tests', function($table) {
                  $table->renameColumn('id_test', 'id');
                  $table->string('id_test', 18);
            });
        }


   public function down()
        {
            Schema::table('tests', function($table) {
                 $table->dropColumn('id_test');
            });
        }

现在只需在命令下方运行

php artisan migrate

注意:不要使用refresh,它会删除数据

要了解有关 Laravel 迁移的更多信息,请参阅:https://laravel.com/docs/5.3/migrations#modifying-columns

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 2019-08-23
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多