這很容易。只需定義一個工廠。讓我們來看看默認出廠 與laravel 5.5
文件:數據庫/工廠/ ModelFacotry.php
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
// Add this line to original factory shipped with laravel.
$faker->seed(123);
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
然後用補鍋匠來測試它:
[email protected] ~/demo> php artisan tinker
Psy Shell v0.8.1 (PHP 7.1.8 — cli) by Justin Hileman
>>> $user = factory(App\User::class)->make()
=> App\User {#880
name: "Jessy Doyle",
email: "[email protected]",
}
>>> $user = factory(App\User::class)->make()
=> App\User {#882
name: "Jessy Doyle",
email: "[email protected]",
}
Laravel文檔:
how to define and use factory
Seeding
這沒有按預期工作。在生成多個工廠實例時,除非使用唯一選項,否則它會生成具有相同名稱和電子郵件的相同用戶。有沒有辦法避免這種情況? –
要繼續以前的評論 - 即使使用唯一()它也不會生成相同的條目:( –
@PetarVasilev對不起,沒有unique(),你會得到相同的faker數據。 –