美文网首页
Laravel数据填充

Laravel数据填充

作者: 老王谈编程 | 来源:发表于2017-11-23 09:59 被阅读0次

    框架:Laravel
    版本:5.5.21

    • 生成Factory
    $ php artisan make:factory StudentsFactory
    
    • 生成Seeder
    $ php artisan make:seeder StudentsTableSeeder
    
    • 填充Factory生成规则:database/factories/StudentFactory
    $factory->define(Student::class, function (Faker $faker) {
        $time = date('Y-m-d H:i:s');
        return [
            'name' => $faker->unique()->name,
            'age' => rand(1,120),
            'sex' => rand(0,2),
            'created_at' => $time,
            'updated_at' => $time,
        ];
    });
    
    • 填充Seeder数据:database/seeds/StudentsTableSeeder
    public function run()
    {
        $students = factory(\App\Models\Student::class)->times(300)->make();
        \App\Models\Student::insert($students->toArray());
    }
    
    • 添加Seeder到DatabaseSeeder:database/seeds/StudentsTableSeeder
    public function run()
    {
        $this->call(StudentsTableSeeder::class);
    }
    
    • 运行数据填充命令,收工
    $ php artisan db:seed --class=StudentsTableSeeder
    

    相关文章

      网友评论

          本文标题:Laravel数据填充

          本文链接:https://www.haomeiwen.com/subject/sjgavxtx.html