1 回答
TA贡献1830条经验 获得超9个赞
首先,您根本不需要 addReference/getReference,因为您使用一个固定文件。因此,在您的情况下,您只需保存对象并在设置器中使用它们,例如:
in loadUsers:
public function loadUsers(ObjectManager $manager)
{
foreach (self::USERS as $userData)
{
$user = new User();
///...
$manager->persist($user);
$this->users[$userData['username']] = $user;
}
$manager->flush();
}
and in loadTheme:
$theme->setUser($this->users[self::USERS[rand(0, count(self::USERS) - 1)]['username']]);
您不需要引用,因为您可以访问对象,当夹具位于单独的文件中时,引用非常有用,因为这样您就无法访问在不同夹具文件中创建的对象。此处描述: https: //symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#sharing-objects- Between-fixtures 。
但是假设您想使用引用,我将尝试提供指导来修复您已有的代码。您说通过引用加载用户适用于主题:
$theme->setUser($this->getReference(self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
它有效,因为您在以下位置添加了引用loadUsers:
$this->addReference($userData['last_name'], $user);
因此,在loadUsers您获得这些参考资料后:
User objects:
- Goodman
- ...
现在,每当您调用时,$this->getReference('Goodman');您都会获得可以在设置器中使用的 User 对象,例如。设置用户();
但您从未调用addReference来loadTheme保存对主题对象的引用。
添加addReference到loadTheme:
public function loadTheme(ObjectManager $manager)
{
foreach (self::THEMES as $themeDate){
$theme = new Theme();
$theme->setName($themeDate['name']);
// ...
$theme->setUser($this->getReference(
self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
$manager->persist($theme);
$this->addReference($theme->getName(), $theme);
}
$manager->flush();
}
因此,之后loadUsers这些loadThemes参考资料将可用:
User objects:
- Goodman
- ...
Theme objects:
- A theme
- A theme 2
- ...
最后在你的loadSousThemes:
$sousthemes->setUsername($this->getReference(
self::USERS[rand(0, count(self::USERS) - 1)]['last_name']));
$sousthemes->setTheme($this->getReference(
self::THEMES[rand(0, count(self::THEMES) - 1)]['name']));
请注意,我假设这$sousthemes->setUsername()实际上是用于设置 User 对象,而不仅仅是用户名(为什么不称为 setUser?)
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报