イントロダクションIntroduction
シーダ(初期値設定)クラスを使用し、テストデーターをデーターベースに設定するシンプルな方法もLaravelには備わっています。全シーダクラスはdatabase/seedsに保存します。シーダクラスには好きな名前を付けられます。しかしUsersTableSeederなどのような分かりやすい規則に従ったほうが良いでしょう。デフォルトとしてDatabaseSeederクラスが定義されています。このクラスからcallメソッドを使い他の初期値設定クラスを呼び出すことで、シーディングの順番をコントロールできます。Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.
シーダクラス定義Writing Seeders
シーダーを生成するには、make:seeder Artisanコマンドを実行します。フレームワークが生成するシーダーは全てdatabase/seedsディレクトリに設置されます。To generate a seeder, execute the make:seeder Artisan command[/docs/{{version}}/artisan]. All seeders generated by the framework will be placed in the database/seeds directory:
php artisan make:seeder UsersTableSeeder
シーダクラスはデフォルトでrunメソッドだけを含んでいます。このメソッドはdb:seed Artisanコマンドが実行された時に呼びだされます。runメソッドの中でデータベースに何でも好きなデーターを挿入できます。クエリビルダでデータを挿入することも、もしくはEloquentモデルファクトリを使うこともできます。A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command[/docs/{{version}}/artisan] is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder[/docs/{{version}}/queries] to manually insert data or you may use Eloquent model factories[/docs/{{version}}/database-testing#writing-factories].
">Tip!! データベースシーディング時、複数代入の保護は自動的に無効になります。{tip} Mass assignment protection[/docs/{{version}}/eloquent#mass-assignment] is automatically disabled during database seeding.
例として、Laravelのインストール時にデフォルトで用意されているDatabaseSeederクラスを変更してみましょう。runメソッドにデータベースINSERT文を追加します。As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:
<?php
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
/**
* データベース初期値設定の実行
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => Str::random(10),
'email' => Str::random(10).'@gmail.com',
'password' => bcrypt('password'),
]);
}
}
">Tip!!
runメソッドの引数として、タイプヒントにより必要な依存を指定できます。それらはLaravelのサービスコンテナにより、自動的に依存解決されます。{tip} You may type-hint any dependencies you need within therunmethod's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].
モデルファクトリの利用Using Model Factories
もちろんそれぞれのモデルシーダで属性をいちいち指定するのは面倒です。代わりに大量のデータベースレコードを生成するのに便利なモデルファクトリが使用できます。最初にモデルファクトリのドキュメントを読んで、どのように定義するのかを学んでください。ファクトリが定義できれば、データベースにレコードを挿入するfactoryヘルパ関数が利用できます。Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories[/docs/{{version}}/database-testing#writing-factories] to conveniently generate large amounts of database records. First, review the model factory documentation[/docs/{{version}}/database-testing#writing-factories] to learn how to define your factories. Once you have defined your factories, you may use the factory helper function to insert records into your database.
例として50件のレコードを生成し、それぞれのユーザーへリレーションを付加してみましょう。For example, let's create 50 users and attach a relationship to each user:
/**
* データベース初期値設定の実行
*
* @return void
*/
public function run()
{
factory(App\User::class, 50)->create()->each(function ($user) {
$user->posts()->save(factory(App\Post::class)->make());
});
}
追加のシーダ呼び出しCalling Additional Seeders
DatabaseSeederクラスの中で追加のシーダクラスを呼び出すcallメソッドが使えます。callメソッドを使うことで、圧倒されるぐらい大きな1ファイルを使う代わりに、データベースシーディングを複数のファイルへ分割できます。実行したいシーダクラス名を渡します。Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Pass the name of the seeder class you wish to run:
/**
* データベース初期値設定の実行
*
* @return void
*/
public function run()
{
$this->call([
UsersTableSeeder::class,
PostsTableSeeder::class,
CommentsTableSeeder::class,
]);
}
シーダの実行Running Seeders
シーダクラスを書き上げたら、Composerのオートローダを再生成するために、dump-autoloadコマンドを実行する必要があります。Once you have written your seeder, you may need to regenerate Composer's autoloader using the dump-autoload command:
composer dump-autoload
データベースへ初期値を設定するためにdb:seed Artisanコマンドを使用します。デフォルトでdb:seedコマンドは、他のシーダクラスを呼び出すDatabaseSeederクラスを実行します。しかし特定のファイルを個別に実行したい場合は、--classオプションを使いシーダを指定してください。Now you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:
php artisan db:seed
php artisan db:seed --class=UsersTableSeeder
もしくはマイグレーションをロールバックし再実行するmigrate:refreshコマンドを使っても、データベースに初期値を設定できます。このコマンドはデータベースを完全に作成し直したい場合に便利です。You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:
php artisan migrate:refresh --seed
実働環境でのシーダの強制実行Forcing Seeders To Run In Production
シーディング操作ではデータが変更されたり、失われる場合があります。実働環境のデータベースに対してシーディングコマンドが実行されるのを防ぐために、シーダを実行する前に確認のプロンプトが表示されます。プロンプトを出さずにシーダを強行する場合は、--forceフラグを使います。Some seeding operations may cause you to alter or lose data. In order to protect you from running seeding commands against your production database, you will be prompted for confirmation before the seeders are executed. To force the seeders to run without a prompt, use the --force flag:
php artisan db:seed --force