Laravel 工厂如何从您的数据库种子文件中调用它们
Laravel Factories how to call them from your database seeder file
如何从数据库播种机调用 factorie 文件我查看了 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),
];
});
数据库播种
php artisan db:seed
在 laravel 路径中...同样,如果您已经播种,则必须清理(确定是否没有重要数据)
php artisan migrate:refresh
这里仔细:)
如何从数据库播种机调用 factorie 文件我查看了 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),
];
});
数据库播种
php artisan db:seed
在 laravel 路径中...同样,如果您已经播种,则必须清理(确定是否没有重要数据)
php artisan migrate:refresh
这里仔细:)