Laravel工厂如何从数据库种子文件中调用它们

时间:2019-02-22 13:48:24

标签: php laravel-5.7 laravel-seeding

如何从数据库播种机中调用工厂文件,我查看了laravel文档,并尝试使用此代码

https://laravel.com/docs/5.7/seeding

   factory(App\User::class, 50)->create()->each(function ($user) {
        $user->posts()->save(factory(App\Post::class)->make());
    });

但是它没有用,所以我的问题是我如何从地雷数据库种子文件中调用地雷,以便我可以从命令行执行它们?

数据库搜索器

  <?php

 use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
 {
/**
 * Seed the application's database.
 *
 * @return void
 */
public function run()
{
    Eloquent::unguard();

    $this->call(UserFactory::class);
    $this->call(PostFacory::class);
    $this->call(ProfileFacory::class);

    $this->command->info("Database seeded.");
    Eloquent::reguard();
  }
 }

用户工厂

  <?php

  use Faker\Generator as Faker;

  $factory->define(App\User::class, function (Faker $faker) {
return [
    'name' => $faker->name,
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => bcrypt('password'),
    'remember_token' => str_random(10),
];
});

1 个答案:

答案 0 :(得分:0)

数据库种子为

php artisan db:seed  

在laravel路径中...如果已经播种,也必须清理(确保没有重要数据)

php artisan migrate:refresh 

小心在这里:)