Laravel的Faker从另一家工厂追​​加数据

时间:2017-05-10 14:38:23

标签: laravel seeding faker laravel-seeding

$factory->define(App\Client::class, function (Faker\Generator $faker) {
    static $password;

    $company_name = $faker->Company;

    return [
        'name' => $company_name,
        'short_name' => substr($company_name, 0, 3),
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});



$factory->define(App\Campaign::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'unique_id' => $faker->numerify('ABC###'),
        'client' => function() {
            return factory('App\Client')->create()->id;
        }

    ];
});

我正在产生客户和活动。一个客户可以有多个广告系列

如何从公司获取 short_name 并将其传递给广告系列类,以便我可以将其附加到随机字符串中以在客户端中创建唯一ID?

1 个答案:

答案 0 :(得分:2)

你几乎就在那里。您不需要在广告系列课程中使用匿名功能,您只需直接引用factory即可。在Campaign工厂中使用变量,只需引用您需要的任何值。

$factory->define(App\Campaign::class, function (Faker\Generator $faker) {
    $client = factory(App\Client::class)->create();

    return [
        'unique_id' => $faker->numerify('ABC###') . $client->short_name,
        'client' => $client->id

    ];
});