Home » Php » php – doctrine 2 persist tries to insert existing items instead of updating them

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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);
}
How to&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();