我有这个模型工厂生成新的联系人,它使用随机company_id
:
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker)
{
$company_id = Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => $company_id,
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
我在种子中使用它是可以的:
factory(App\Models\Contact::class)->create();
但是为了测试,我需要以某种方式将$company_id
传递给工厂,为具体的company_id
创建联系人(我知道我可以->create(['company_id', $company_id])
)但这只会重写来自Contact的company_id。
当我选择lead_id
时,我还需要知道当前company_id
。
如何将company_id作为参数传递给工厂?
答案 0 :(得分:2)
尝试使用此示例:
$factory->define(App\Models\Contact::class, function ($faker, $params) {
$company_id = $params['company_id'];
....
});
这是一个新对象:
$newContact = factory(App\Models\Contact::class)->make(['company_id' => $current_company_id]);
答案 1 :(得分:1)
取决于您的Laravel版本,它会有所不同。
对于laravel 5.1 https://github.com/laravel/framework/issues/9245
您将需要检查是否手动传递
// Testcase
$company = factory(App\Models\Company::class)->create();
factory(App\Models\Contact::class)->create(['company_id' => $company->id]);
// Factory
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker, $attribues) {
// Manually check if id is passed
$company_id = (isset($attribues['company_id'])) ?: Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => $company_id,
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
对于Laravel 5.2及更高版本,您只需传递id https://laravel.com/docs/5.5/database-testing#relationships
// Testcase
$company = factory(App\Models\Company::class)->create();
factory(App\Models\Contact::class)->create(['company_id' => $company->id]);
// Factory
$factory->define(App\Models\Contact::class, function (Faker\Generator $faker, $attribues) {
// Manually check if id is passed
$company_id = (isset($attribues['company_id'])) ?: Company::all()->random()->id;
return [
'firstname' => $faker->firstName,
'lastname' => $faker->lastName,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'company_id' => function(){
return factory(\App\Models\Company::class)->create()
},
'lead_id' => \App\Models\Lead::where('company_id', $company_id)->get()->random()->id,
];
});
因此,对于您的情况,请先获取随机的company_id并将其传递给工厂。取决于您的Larval版本,更改ContactModel工厂。或者,如果您有可以查询的关系,也可以这样做。
// If you have a relation
$contact = factory(App\Models\Contact::class)->create();
$company_id = $contact->company->id;