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

前端之家收集整理的这篇文章主要介绍了php – 在保留测试数据的同时在laravel 5.2迁移中添加字段的过程是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_6@ 我正在学习并尝试使用laravel 5.2,我很困惑如何在表格中添加字段.

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

$table->string('content');

然后运行该命令

PHP artisan migrate:refresh

新字段将出现在表中但测试数据(例如用户表中的用户将被截断)

问题是:

1)向表中添加新字段的正确方法(最佳实践)是什么?
2)如何将测试数据保存在所有表中,例如用户表中的用户

谁知道该怎么办?

解决方法

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

您的应用程序已经与使用它的人一起使用,并且您不想丢失其数据:您只需进行新的迁移并使用相应的操作提供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后,它将重置数据库并使用初始/测试数据对其进行播种.

猜你在找的Laravel相关文章