Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine 2 persist tries to insert existing items instead of updating them

Tags:

php

doctrine

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);
}
like image 639
Geoffrey De Vylder Avatar asked Jun 20 '11 13:06

Geoffrey De Vylder


1 Answers

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.

$rule = new CompositionRule;
$block = $entityManager->merge($block); //it's important to use result of function, not the same element
$entityManager->persist($role);
$entityManager->flush();
like image 123
Kamil Avatar answered Oct 26 '22 09:10

Kamil