原则 2 persist 尝试插入现有项目而不是更新它们
我正在从原则 1.2 切换到 2.x,但遇到了一个奇怪的问题。
我有一个实体 CompositionRule,它有一个属性 $buildingBlock,指向 BuildingBlock 实体。
我设置了此属性,使其指向从数据库中获取的现有 BuildingBlock。
当我保留主对象(CompositionRule)时,entitymanager 尝试创建一个新的 BuildingBlock 项并将其插入数据库中,而不是仅仅接受它已经存在并忽略它。
当你执行 $entity->save(); 时,我没有看到我在原则 1.2 中遗漏了什么;所有底层对象均已正确处理。
以下是我的映射/代码的一些部分:
CompositionRule:
<many-to-one field="buildingBlock" target-entity="BuildingBlock">
<cascade><cascade-all /></cascade>
</many-to-one>
..
public function setBuildingBlock($buildingBlock) {
$buildingBlock->addCompositionRule($this);
$this->buildingBlock = $buildingBlock;
}
BuildingBlock
<one-to-many field="compositionRules" target-entity="CompositionRule" mapped-by="buildingBlock">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
public function addCompositionRule($rule) {
$this->compositionRules->add($rule);
}
I'm making the switch from doctrine 1.2 to 2.x and am running into a strange problem.
I have an entity CompositionRule that has an attribute $buildingBlock, pointing to a BuildingBlock entity.
I set this attribute, making it point to an existing BuildingBlock, which I fetch from the database.
When I persist the main object (CompositionRule), the entitymanager tries to create a new BuildingBlock item and insert it in the database instead of just accepting that it already exists and ignoring it.
I don't see what I'm missing here as in doctrine 1.2 when you executed $entity->save(); all the underlying objects were correctly handled.
Here are some parts of my mappings / code:
CompositionRule:
<many-to-one field="buildingBlock" target-entity="BuildingBlock">
<cascade><cascade-all /></cascade>
</many-to-one>
..
public function setBuildingBlock($buildingBlock) {
$buildingBlock->addCompositionRule($this);
$this->buildingBlock = $buildingBlock;
}
BuildingBlock
<one-to-many field="compositionRules" target-entity="CompositionRule" mapped-by="buildingBlock">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
public function addCompositionRule($rule) {
$this->compositionRules->add($rule);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道这是一个老问题,但我最近遇到了同样的问题,所以它可能会有所帮助。
它是由于您的实体的“分离”状态而发生的。您应该使用doctrine::merge() 函数来解决这个问题。
I uderstood that it's an old question, but I had the same problem recently, so it can helps maybe.
It occurs due to "detached" status of your entity. You should use doctrine::merge() function to fix this.