Laravel模型工厂

问题描述:

我试图设立法克尔在Laravel默认的种子,以这种方式(而不是在Laravel)通常实现:根据法克尔的GitHubLaravel模型工厂

<?php 
$faker = Faker\Factory::create(); 
$faker->seed(1234); 

我想这样做,这样我就可以得到每次生成相同的数据,这样我可以写一些单元测试,但我不知道如何在Laravel中做到这一点。我检查了Laravel的文档并尝试使用Google搜索,但我什么也没找到。

这很容易。只需定义一个工厂。让我们来看看默认出厂 与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

+0

这没有按预期工作。在生成多个工厂实例时,除非使用唯一选项,否则它会生成具有相同名称和电子邮件的相同用户。有没有办法避免这种情况? –

+0

要继续以前的评论 - 即使使用唯一()它也不会生成相同的条目:( –

+0

@PetarVasilev对不起,没有unique(),你会得到相同的faker数据。 –