生成工厂类文件
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