11장 데이터베이스 시딩
11.1. 시더 만들기
$ php artisan make:seeder UsersTableSeeder
class UsersTableSeeder extends Seeder
{
public function run()
{
App\User::create([
'name' => sprintf('%s %s', str_random(3), str_random(4)),
'email' => str_random(10) . '@example.com',
'password' => bcrypt('password'),
]);
}
}
$ php artisan db:seed --class=UsersTableSeeder
11.2. 모델 팩터리
$ php artisan tinker
>>> factory(App\User::class)->make();
>>> factory(App\User::class)->make(['name' => 'Foo']);
11.2.1. 시더 수정
class UsersTableSeeder extends Seeder
{
public function run()
{
factory(App\User::class, 5)->create();
}
}
11.2.2. 모델 팩터리 추가
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'password' => bcrypt('password'),
'remember_token' => str_random(10),
];
});
$factory->define(App\Article::class, function (Faker\Generator $faker) {
$date = $faker->dateTimeThisMonth;
return [
'title' => $faker->sentence(),
'content' => $faker->paragraph(),
'created_at' => $date,
'updated_at' => $date,
];
});
$ php artisan make:seeder ArticlesTableSeeder
class ArticlesTableSeeder extends Seeder
{
public function run()
{
$users = App\User::all();
$users->each(function ($user) {
$user->articles()->save(
factory(App\Article::class)->make()
);
});
}
}
11.3. 마스터 시더
class DatabaseSeeder extends Seeder
{
public function run()
{
if (config('database.default') !== 'sqlite') {
DB::statement('SET FOREIGN_KEY_CHECKS=0');
}
App\User::truncate();
$this->call(UsersTableSeeder::class);
App\Article::truncate();
$this->call(ArticlesTableSeeder::class);
if (config('database.default') !== 'sqlite') {
DB::statement('SET FOREIGN_KEY_CHECKS=1');
}
}
}
$ php artisan db:seed
11.4. 마이그레이션과 시딩
$ php artisan migrate:refresh --seed
11.5. 마치며
$ git commit -m '데이터베이스 시딩'
$ git tag 1011-seeding