LoginSignup
0
0

Laravel勉強日記

Posted at

laravel勉強日記

シーディングを利用してデータを一括挿入

シーダーを作成するには以下のコマンド

sail artisan make:seeder TweetsSeeder

database/seeder にTweetSeederクラスが作成される

DBにデータが挿入される流れ

① database/seederに作成されたデータを挿入するためのファイルを作成する。

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;


class TweetsSeeder extends Seeder
{
    public function run()
    {
        DB::table('tweets')->insert([
            'content' => Str::random(100),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}

こんな挿入するためのファイルを書く

2,さっきのファイルを呼び出すためのファイルを作成する

public function run()
{
    // \App\Models\User::factory(10)->create();
    $this->call([TweetsSeeder::class]);
}

#### ③最後にシーダーを実行するArtisanコマンドを実行する

sail artisan db:seed

個別にシーダーを呼び出す際には、classオプションを使う

sail artisan db:seed --class=TweetsSeeder
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0