2017-09-29 42 views
0

我試圖設立法克爾在Laravel默認的種子,以這種方式(而不是在Laravel)通常實現:根據法克爾的GitHubLaravel模型工廠

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

我想這樣做,這樣我就可以得到每次生成相同的數據,這樣我可以寫一些單元測試,但我不知道如何在Laravel中做到這一點。我檢查了Laravel的文檔並嘗試使用Google搜索,但我什麼也沒找到。

回答

1

這很容易。只需定義一個工廠。讓我們來看看默認出廠 與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數據。 –