Laravel 的 Faker 从另一个工厂获取附加数据
Faker with Laravel taking appending data from another factory
$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 并将其传递给活动 class,以便我可以将其附加到随机字符串以在客户端中创建唯一 ID?
你快到了。您不需要在活动 class 中使用匿名函数,您可以直接引用 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
];
});
$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 并将其传递给活动 class,以便我可以将其附加到随机字符串以在客户端中创建唯一 ID?
你快到了。您不需要在活动 class 中使用匿名函数,您可以直接引用 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
];
});