イントロダクションIntroduction
Laravelは、シードクラスを使用してデータベースにデータをシード(種をまく、初期値の設定)する機能を持っています。すべてのシードクラスはdatabase/seeders
ディレクトリに保存します。デフォルトで、DatabaseSeeder
クラスが定義されています。このクラスから、call
メソッドを使用して他のシードクラスを実行し、シードの順序を制御できます。Laravel includes the ability to
seed your database with data using seed classes. All
seed classes are stored in the
database/seeders
directory. 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.
複数代入は、データベースのシード中では自動的に無効になります。[!NOTE]
Note:
Mass assignment protection[/docs/{{version}}/eloquent#mass-assignment] is automatically disabled during database seeding.
シーダクラス定義Writing Seeders
シーダを生成するには、make:seeder
Artisanコマンドを実行します。フレームワークが生成するシーダはすべてdatabase/seeders
ディレクトリに設置します。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/seeders
directory:
php artisan make:seeder UserSeeder
シーダクラスには、デフォルトで1つのメソッド、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}}/eloquent-factories].
例として、デフォルトのDatabaseSeeder
クラスを変更し、データベース挿入文をrun
メソッドに追加しましょう。As an example, let's modify the
default DatabaseSeeder
class and add a
database insert statement to the run
method:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class DatabaseSeeder extends Seeder
{
/**
* データベースに対するデータ設定の実行
*/
public function run(): void
{
DB::table('users')->insert([
'name' => Str::random(10),
'email' => Str::random(10).'@example.com',
'password' => Hash::make('password'),
]);
}
}
Note:
run
メソッドの引数として、タイプヒントにより必要な依存を指定できます。それらはLaravelのサービスコンテナが自動的に依存解決します。[!NOTE]
You may type-hint any dependencies you need within therun
method's signature. They will automatically be resolved via the Laravel service container[/docs/{{version}}/container].
モデルファクトリの利用Using Model Factories
当然それぞれのモデルシーダで属性をいちいち指定するのは面倒です。代わりに大量のデータベースレコードを生成するのに便利なモデルファクトリが使用できます。最初にモデルファクトリのドキュメントを読んで、どのように定義するのかを学んでください。Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories[/docs/{{version}}/eloquent-factories] to conveniently generate large amounts of database records. First, review the model factory documentation[/docs/{{version}}/eloquent-factories] to learn how to define your factories.
例として、それぞれに1つの関連する投稿がある50人のユーザーを作成しましょう。For example, let's create 50 users that each has one related post:
use App\Models\User;
/**
* データベースに対するデータ設定の実行
*/
public function run(): void
{
User::factory()
->count(50)
->hasPosts(1)
->create();
}
追加のシーダ呼び出しCalling Additional Seeders
DatabaseSeeder
クラス内で、call
メソッドを使用して追加のシードクラスを実行できます。call
メソッドを使用すると、データベースのシードを複数のファイルに分割して、単一のシーダークラスが大きくなりすぎないようにできます。call
メソッドは、実行する必要のあるシーダークラスの配列を引数に取ります。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 too
large. The call
method accepts an array
of seeder classes that should be
executed:
/**
* データベースに対するデータ設定の実行
*/
public function run(): void
{
$this->call([
UserSeeder::class,
PostSeeder::class,
CommentSeeder::class,
]);
}
モデルイベントのミュートMuting Model Events
シードの実行中に、モデルがイベントをディスパッチしないようにしたい場合があります。これはWithoutModelEvents
トレイトを使って実現できます。WithoutModelEvents
トレイトを使うと、たとえcall
メソッドで追加のシードクラスが実行されても、モデルのイベントがディスパッチされないようにできます。While running seeds, you may want
to prevent models from dispatching events. You may
achieve this using the
WithoutModelEvents
trait. When used,
the WithoutModelEvents
trait ensures no
model events are dispatched, even if additional seed
classes are executed via the call
method:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* データベースに対するデータ設定の実行
*/
public function run(): void
{
$this->call([
UserSeeder::class,
]);
}
}
シーダの実行Running Seeders
db:seed
Artisanコマンドを実行して、データベースに初期値を設定します。デフォルトでは、db:seed
コマンドはDatabase\Seeders\DatabaseSeeder
クラスを実行します。このクラスから他のシードクラスが呼び出される場合があります。ただし、--class
オプションを使用して、個別に実行する特定のシーダークラスを指定できます。You may execute the
db:seed
Artisan command to seed your
database. By default, the db:seed
command runs the
Database\Seeders\DatabaseSeeder
class,
which may in turn invoke 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=UserSeeder
migrate:fresh
コマンドを--seed
オプションと組み合わせて使用してデータベースをシードすることもできます。これにより、すべてのテーブルが削除され、すべてのマイグレーションが再実行されます。このコマンドは、データベースを完全に再構築するのに役立ちます。特定のシーダーの実行を指定するには、--seeder
オプションを使用します。You may also seed your database
using the migrate:fresh
command in
combination with the --seed
option,
which will drop all tables and re-run all of your
migrations. This command is useful for completely
re-building your database. The --seeder
option may be used to specify a specific seeder to
run:
php artisan migrate:fresh --seed
php artisan migrate:fresh --seed --seeder=UserSeeder
実働環境でのシーダの強制実行Forcing Seeders to Run in Production
一部のシード操作により、データが変更または失われる場合があります。本番データベースに対してシードコマンドを実行しないように保護するために、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 in the
production
environment. To force the
seeders to run without a prompt, use the
--force
flag:
php artisan db:seed --force