我正在学习并尝试使用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后,它将重置数据库并使用初始/测试数据对其进行播种.
标签:php,laravel,laravel-5-2 来源: https://codeday.me/bug/20190628/1312830.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。