php – 在保留测试数据的同时在laravel 5.2迁移中添加字段的过程
发布时间:2020-12-14 19:42:46 所属栏目:大数据 来源:网络整理
导读:我正在学习并尝试使用laravel 5.2,我很困惑如何在表格中添加字段. 我创建了一个名为2016_01_29_093417_create_thread_table.php的迁移文件,每当我想添加一个字段时,我在文件中添加一个代码,例如 $table-string('content'); 然后运行该命令 php artisan migra
我正在学习并尝试使用laravel 5.2,我很困惑如何在表格中添加字段.
我创建了一个名为2016_01_29_093417_create_thread_table.php的迁移文件,每当我想添加一个字段时,我在文件中添加一个代码,例如 $table->string('content'); 然后运行该命令 php artisan migrate:refresh 新字段将出现在表中但测试数据(例如用户表中的用户将被截断) 问题是: 1)向表中添加新字段的正确方法(最佳实践)是什么? 谁知道该怎么办? 解决方法
有两种方法可以做到这一点.
您的应用程序已经与使用它的人一起使用,并且您不想丢失其数据:您只需进行新的迁移并使用相应的操作提供up()和down().例如: <?php use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; 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 IlluminateDatabaseSeeder; 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后,它将重置数据库并使用初始/测试数据对其进行播种. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |