Laravel 5.3模型工厂

时间:2016-12-21 15:52:17

标签: php laravel

关于工厂的简单问题:

ModelFactory:

$myarray=[
'cat1',
'cat2', 
'cat3'   
];



 $factory->define(App\Job::class, function (Faker\Generator $faker) {
        return [
            'title' => $faker->randomElement($myarray),
            'firm_id' => $faker->numberBetween($min = 1, $max = 3),
            'user_id' => $faker->numberBetween($min = 1, $max = 5),
        ];
    });

为什么它不起作用?

另一个简单的问题:是否有可能在工厂中传递$ myarray来自雄辩?

1 个答案:

答案 0 :(得分:5)

您需要使关闭使用数组,以使其可用:)

$myarray = ['cat1', 'cat2', 'cat3'];

$factory->define(App\Job::class, function (Faker\Generator $faker) use ($myarray) {
    return [
        'title' => $faker->randomElement($myarray),
        'firm_id' => $faker->numberBetween($min = 1, $max = 3),
        'user_id' => $faker->numberBetween($min = 1, $max = 5),
    ];
});

这是一些来自php docs的例子:) http://php.net/manual/en/functions.anonymous.php#example-160