【发布时间】:2014-08-09 08:14:14
【问题描述】:
我在 Symfony2 中开发了一些 Fixtures 来像 crons 一样工作,每 5-10 分钟启动一次。那是因为我的应用程序依赖于不断变化的外部 api。
另一方面,api 有一个完全不相关且没有意义的 json 响应,我不能相信所有数据都在每次调用中,所以我有许多可以为空的字段,而不是可以在下一个 cron “也许”更新。我想处理它并存储在相关的数据库中:
我有:
class Hero
{
/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="heroes")
* @ORM\JoinTable(name="heroes_roles")
**/
private $roles;
}
class Role
{
/**
* @ORM\ManyToMany(targetEntity="Hero", mappedBy="roles")
**/
private $heroes;
}
在我的fixture中,连接api并从json获取数据后:
// Roles
$rolesRepository = $manager->getRepository('ProjectStoreBundle:Role');
$rolesIndexedByName = $rolesRepository->getIndexedBy('name');
// Json con info de los heroes
$heroesInfo = json_decode(file_get_contents($this->kernel->locateResource('@ProjectStoreBundle/Resources/doc/heroes_info.json')));
foreach ($array_response['result']['heroes'] as $apiHero) {
$hero = new Hero();
$hero->setId($apiHero['id']);
$hero->setName($apiHero['name']);
...// more normal sets
// Update it if exists
$manager->merge($hero);
// Add his roles
foreach ($heroesInfo->$apiHero['name']->roles as $role) {
if (!empty($rolesIndexedByName[$role])) {
$hero->addRole($rolesIndexedByName[$role]);
}
}
}
$manager->flush();
我尝试过的事情:
- 改变顺序,先添加角色,再合并
- 在 $hero->addRole 上添加逆
- 放置级联{persist}
选项 2:
public function addRole(Role $roles)
{
$roles->addHero($this); // cascade error
$this->roles[] = $roles;
return $this;
}
我可能会原谅一些事情,我在开发应用程序时正在学习 symfony2。
感谢您的建议。
更新
如果我将合并更改为持久,多对多关系将被保存,但我不能使用相同的脚本来更新。
谁能解释一下为什么合并没有创建关系?
【问题讨论】:
标签: php symfony doctrine-orm