Laravel模型工廠填充資料

aba66發表於2021-11-17

生成工廠類檔案

php artisan make:factory TestFactory

*** 編輯database/factories/TestFactory.php

<?php

namespace Database\Factories;

use App\Models\Test;
use Illuminate\Database\Eloquent\Factories\Factory;

class TestFactory extends Factory
{
    protected $model = Test::class;

    public function definition()
    {
        $date_time = $this->faker->date . ' ' . $this->faker->time;
        return [
            'user_id'    => $this->faker->randomElement(['1','2','3']),
            'content'    => $this->faker->text(),
            'created_at' => $date_time,
            'updated_at' => $date_time,
        ];
    }
}

建立TestTableSeeder

php artisan make:seeder TestTableSeeder

*** 編輯database/seeders/StatusesTableSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Test;

class TestTableSeeder extends Seeder
{
    public function run()
    {
        Status::factory()->count(100)->create();
    }
}

呼叫資料填充

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        Model::unguard();

        $this->call(TestTableSeeder::class);

        Model::reguard();
    }
}

資料庫重置、填充

php artisan migrate:refresh --seed
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章