原则2 - 使用PersistentCollection

时间:2014-07-11 21:44:45

标签: php symfony doctrine-orm

我目前正在为一些遗留代码编写测试。我正在处理的其中一个实体包含一对多关系中的ArrayCollection个其他实体。当我在我的灯具中加载数据时,我可以看到关系One侧的实体使用PhpStorm的调试器正确地包含了关系的Many侧的实体。

显然,当ArrayCollection持久存储到数据库时,PersistentCollection会成为PersistentCollection

我正在测试的方法是尝试使用foreach迭代这个新形成的ArrayCollection,但是,没有任何事情发生。根据调试器,该集合包含关系元数据,但不会检索我在原始class Entity1 { private $items; public function __construct() { $this->items = new ArrayCollection(); } public function addItem(Entity2 $item) { $this->items[] = $item; } public function getItems() { return $this->items; } } class Entity2 {} $child1 = new Entity2(); $child2 = new Entity2(); $child3 = new Entity2(); $ent = new Entity1(); $ent->addItem($child1); $ent->addItem($child2); $ent->addItem($child3); // persist them all with the entity manager // end data fixtures // inside a different file, in the method I'm trying to test: $items = $ent->getItems(); foreach ($items as $item) { // nothing happens as $items contains metadata/relationship data, but doesn't (lazy) load // the Entity2 instances } 中输入的值。

伪代码示例(由于NDA):

PersistentCollection

这是coll

中实际屏幕截图

enter image description here

请注意我假设的Entity2集合应该用我的{{1}}个实例填充的内容是空的。

所以,我有点失落。我需要能够访问Entity2实例,但它没有发生。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

为OneToMany配置添加级联参数。如果使用注释:

/**
* @ORM\OneToMany(targetEntity="Entity2", mappedBy="entity1", cascade={"persist"})
*/

将mappedBy参数调整为您的实际实现。

答案 1 :(得分:0)

想出来。

尝试通过向Entity2 Entity1添加ArrayCollection个实例来关联实体并不起作用。 Entity2实例中没有一个具有Entity1的id作为外键。以相反的方式执行操作 - 为每个Entity1手动设置Entity2 - 工作,我现在可以遍历集合。

我不确定这种行为 - 无法通过ArrayCollection创建/强制执行任何关系是定义的行为还是错误,但我想我应该在任何地方发布我的解决方案事件