Readouble

Laravel 8.x データベース:シーディング

イントロダクション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.

lightbulb">Tip!! 複数代入は、データベースのシード中では自動的に無効になります。{tip} 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}}/database-testing#defining-model-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
{
    /**
     * データベースに対するデータ設定の実行
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => Str::random(10),
            'email' => Str::random(10).'@gmail.com',
            'password' => Hash::make('password'),
        ]);
    }
}

lightbulb">Tip!! runメソッドの引数として、タイプヒントにより必要な依存を指定できます。それらはLaravelのサービスコンテナが自動的に依存解決します。{tip} You may type-hint any dependencies you need within the run 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}}/database-testing#defining-model-factories] to conveniently generate large amounts of database records. First, review the model factory documentation[/docs/{{version}}/database-testing#defining-model-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;

/**
 * データベースに対するデータ設定の実行
 *
 * @return void
 */
public function run()
{
    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:

/**
 * データベースに対するデータ設定の実行
 *
 * @return void
 */
public function run()
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
        CommentSeeder::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オプションと組み合わせて使用​​してデータベースをシードすることもできます。これにより、すべてのテーブルが削除され、すべてのマイグレーションが再実行されます。このコマンドは、データベースを完全に再構築するのに役立ちます。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:

php artisan migrate:fresh --seed

実働環境でのシーダの強制実行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

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作