Laravel框架使用Seeder实现自动填充数据功能 本文实例讲述了Laravel框架使用Seeder实现自动填充数据功能。分享给大家供大家参考,具体如下: 要查看代码,可以点击链接:http://github.com/laravel/framework Laravel自动填充数据使用的是Seeder类 call('PostTableSeeder'); Model::reguard(); } } class PostTableSeeder extends Seeder { public function run() { App\Post::truncate(); factory(App\Post::class, 1000)->create(); } } 这里有读者会问:为什么我们不把填充操作都写在自带的DatabaseSeeder的run函数里呢? 因为我们开发一个完整的系统时,可能要填充的数据表有很多张,不希望每次都要大量修改这个run函数。我们还希望每次填充都能保留下这个填充的过程,所以我们宁愿新写一个类,然后用$this->call()函数来调用。 接下来我们来谈谈factory。 文件目录\database\factories\ModelFactory.php $factory->define(App\Post::class, function ($faker) { return [ 'title' => $faker->sentence(mt_rand(3, 10)), 'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))), 'published_at' => $faker->dateTimeBetween('-1 month', '+3 days'), ]; }); 虽然能看懂,但是不知道这个$factory变量是什么?因此去查Factory类找。 在目录\vendor\laravel\framework\src\Illuminate\Database\Eloquent的Factory.php找到源代码 /** * Define a class with a given set of attributes. * * @param string $class * @param callable $attributes * @param string $name * @return void */ public function define($class, callable $attributes, $name = 'default') { $this->definitions[$class][$name] = $attributes; } /** * Create an instance of the given model and persist it to the database. * * @param string $class * @param array $attributes * @return mixed */ public function create($class, array $attributes = []) { return $this->of($class)->create($attributes); } 开始填充数据,我们还是使用artisan命令行 php artisan db:seed 这个命令会执行你写在DatabaseSeeder.php里面所有的类的run函数,如果以后项目复杂了,没有必要执行已经执行过的,所以在命令行后面加参数,只要执行某个类的run函数即可 php artisan db:seed --class=你要执行的类名称 更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》 希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。