我有一个创建StreetAddresses的工厂,我想在创建CreditCard的工厂中使用它。
良好:这的行为符合预期,为Street_address创建了一个带有stdClass的CreditCard对象,并且所有属性都很好。
<?php
use FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;
$factory->define(CreditCard::class, function (\Faker\Generator $faker){
$street_address = factory(StreetAddress::class)->make();
return [
'customer_id' => User::root()->getKey(),
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
// LOOK HERE: this works
'street_address' => function () use ($street_address) { return (object) $street_address->toArray(); }
];
});
效果不太好:街道地址返回null。
<?php
use FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
use FuquIo\LaravelUser\Access\User;
$factory->define(CreditCard::class, function (\Faker\Generator $faker){
$street_address = factory(StreetAddress::class)->make();
return [
'customer_id' => User::root()->getKey(),
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
// LOOK HERE AGAIN: this makes a null
'street_address' => function () use ($street_address) { return $street_address; }
];
});
我想要的是产生一个将StreetAddress作为属性的信用卡。
更新:根据第一个建议的解决方案,我(重新)尝试了直接方法。仍然为空。
use FuquIo\LaravelAccounting\Orm\CreditCard;
use FuquIo\LaravelCommonRelatables\Locatable\StreetAddress;
$factory->define(CreditCard::class, function (\Faker\Generator $faker){
//$street_address = factory(StreetAddress::class)->make();
return [
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
// 'street_address' => function () use ($street_address) { return (object) $street_address->toArray(); }
'street_address' => factory(StreetAddress::class)->make()
];
});
仅供参考:在我经过的所有情况下,调试器都会显示正确的类。
答案 0 :(得分:-2)
假设您还有一家StreetAddress
的工厂,那么您应该能够执行以下操作:
$factory->define(CreditCard::class, function (\Faker\Generator $faker){
return [
'cardholder' => $faker->firstName . ' ' . $faker->lastName,
'nick_name' => $faker->company,
'street_address' => function () {
return factory(App\StreetAddress::class)->create()->toArray();
}
];
});