在保留测试数据的同时在 laravel 5.2 迁移中添加字段的过程是什么?

what is the procedure to add field in laravel 5.2 migration while keeping the testing data?

我正在学习并尝试使用 laravel 5.2,我对如何在 table 中添加字段感到困惑。

我创建了一个名为 2016_01_29_093417_create_thread_table.php 的迁移文件,每次我想添加一个字段时,我都会在文件中添加一个代码,例如

$table->string('content');  

然后 运行 命令

php artisan migrate:refresh

新字段将出现在 table 中,但测试数据(例如用户 table 中的用户将被 t运行 分类)

问题是:

1) 向 table 添加新字段的正确方法(最佳做法)是什么? 2) 如何保存所有 table 的测试数据,例如 users in users table?

有人知道怎么做吗?

好吧,您需要为每个列更改创建一个新的迁移

你需要使用migrate

migration:refresh 将重新设置数据库并再次播种

如果您希望保留测试数据并节省再次输入数据的时间,我建议您使用播种机和模型工厂 https://laravel.com/docs/5.1/seeding#using-model-factories

有两种方法可以做到这一点。

您的应用程序已经上线 并且有人在使用它,您不想丢失他们的数据:您只需进行新的迁移并提供 up()down()进行相应的操作。例如:

<?php

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

class UsersNewField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('email');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('email');
        });
    }
}

在您 运行 php artisan migrate 之后,它将只是 运行 最新的迁移。

您的应用程序仍在开发中,目前还没有人使用它:您使用种子将测试数据填充到数据库中,并根据需要编辑初始迁移。例如:

<?php

use Illuminate\Database\Seeder;

class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => 'First User',
            'email' => 'user1@example.com',
            'password' => bcrypt('somepass9019'),
        ]);

        DB::table('users')->insert([
            'name' => 'Second User',
            'email' => 'user2@example.com',
            'password' => bcrypt('somepass2039'),
        ]);

        DB::table('users')->insert([
            'name' => 'Third User',
            'email' => 'user3@example.com',
            'password' => bcrypt('somepass0534'),
        ]);
    }
}

在您 运行 php artisan migrate:refresh --seed 之后,它将重置数据库并使用 initial/testing 数据为它播种。