如何将变量传递给Laravel的Factory?

时间:2019-03-07 12:01:06

标签: laravel eloquent factory

如何/可以有选择地将数字传递给Laravel工厂,以便如果我不提供数字,它会执行默认的操作,并且如果我使用它们,会使用数字吗?

例如,我有一个Student模型。它会产生一个随机的男性或女性学生,并有50%的机会使用Faker来产生中间名。看起来像这样:

$factory->define(App\Student::class, function (Faker $faker) {

    $gender = $faker->randomElement($array = array ('m','f'));
    $has_middle_name = $faker->boolean($chanceOfGettingTrue = 50);
    $student = [];

    if ($gender == 'm') {
        $student['first_name'] = $faker->firstNameMale;
        if ($has_middle_name) {
            $student['middle_name'] = $faker->middleNameMale;
        }
    } else {
        $student['first_name'] = $faker->firstNameFemale;
        if ($has_middle_name) {
            $student['middle_name'] = $faker->firstNameMale;
        }       
    }

    $student['last_name'] = $faker->lastName;
    $student['gender'] = $gender;

    $student['birth_date'] = $faker->dateTimeBetween($startDate = '-18 years', $endDate = '-4 years', $timezone = null);

    return $student;

});

我已经看到我可以使用State作为传递var的方法。例如,我可以做这样的事情:

$student = factory(App\Student::class)->state('male')->make();

这将调用我的工厂的这一位,因此将first_namemiddle_namegender属性修改为与male一致:

$factory->state(App\Student::class, 'male', function (Faker $faker) {

    $student = [];
    $student['first_name'] = $faker->firstNameMale;
    $has_middle_name = $faker->boolean($chanceOfGettingTrue = 50);
    if ($has_middle_name) {
        $student['middle_name'] = $faker->middleNameMale;
    }    
    $student['gender'] = 'm';

    return $student;

});

但是,上面的代码创建的学生年龄在4到18岁之间。如果我想创建一个特定年龄的学生怎么办?我知道我可以这样做,使一个8到9之间的学生:

$birth_date = $faker->dateTimeBetween($startDate = '-9 years', $endDate = '-9 years', $timezone = null);
$student = faker(App\Student::class)->make(['birth_date' => $birth_date]);

但是我宁愿做这样的事情:

$student = faker(App\Student::class)->make($minAge = 8, $maxAge = 9);

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以在学生模型工厂中定义min_agemax_age并使用以下代码:

$student = faker(App\Student::class)->make(['min_age' => 8, 'max_age' => 9]);