Migration创建表
这里以blogs表举例
命令
php artisan make:migration create_blogs --create=blogs
编辑 /database/migrations/ 下的 create_blogs文件
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
by the way 在我创建数据表的时候总是会给我报错说我的varchar的字符串长度怎么怎么样的报错,这是的修改方案在App\Providers\AppServiceProvider文件中修改
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(200);
}
确保你的数据库中没有blogs表
php artisan migrate
这时你所需要的的数据表就建好了
使用模型工厂 Factory 来插入虚构的数据
创建模型工厂
php artisan make:factory BlogsFactory --model=Blogs
顺便生成模型
php artisan make:model Blogs
编辑模型工厂 /database/factories下的BlogFactory文件
public function definition()
{
return [
'title' => $this->faker->name,
'content' => $this->faker->text,
];
}
使用 tinker 模式调试代码
php artisan tinker
当命令提示符变为 “>>>” 时,你就处于tinker模式下了
//命令生成模拟数据,记得模型的路由一定要写正确
App\Models\Blogs::factory()->create();
//生成多条数据
App\Models\Blogs::factory()->count(100)->create();
想要生成其他表的数据,就将路由模型换一下就好了(【ctrl】+【c】 可退出tinker)
使用 Seeder 一次性完成多个数据库的批量虚拟数据插入
创建seeder
php artisan make:seeder BlogsTableSeeder
修改 /database/seeds/下的BlogsTableSeeder文件和DatabaseSeeder.php文件
BlogsTableSeeder文件
use App\Models\Blogs;
public function run()
{
\App\Models\Blogs::factory(50)->create(); //向users表中插入50条模拟数据
}
DatabaseSeeder.php文件
public function run()
{
// \App\Models\User::factory(10)->create();
$this->call(BlogsTableSeeder::class);
}
然后输入命令
php artisan migrate:refresh --seed
如果需要多个表格的话,可以按照Blogs操作多建造几个