1
votes

I'm trying to save a deserialized OneToMany connection, but doctrine leaves the id-field of the parent item ($parent) empty.

class MyParent
{
    /**
     * @ORM\OneToMany(targetEntity="MyChild", mappedBy="parent", cascade={"persist"})
     *
     * @Serializer\Expose
     * @Serializer\SerializedName("Children")
     * @Serializer\Type("ArrayCollection<MyNamespace\MyChild>")
     * @Serializer\XmlList(entry="Children")
     *
     * @var \Doctrine\Common\Collections\ArrayCollection
     */
    private $children;

}

class MyChild
{
    /**
     * @var MyParent
     *
     * @ORM\ManyToOne(targetEntity="MyParent", inversedBy="children")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     * })
     */
    private $parent;
}

I'm trying this by using the JMS Serializer:

$entity = $serializer->deserialize($myXmlAsString, 'MyNamespace\MyParent', 'xml');
$entityManager->persist($entity);
$entityManager->flush($entity);

The result: All data is saved into database but the column parent_id of children is null!

The xml does not contain any ids. The ids are excluded from (de)serialization anyway, because I want to ignore them.

What is wrong in my configuration?

1

1 Answers

1
votes

I think you should merge your entity before persisting it.

Try adding $entity = $entityManager->merge($entity); before the persist and add , "merge" to the cascade option

From the manual @ http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#merging-entities

Merging entities refers to the merging of (usually detached) entities into the context of an EntityManager so that they become managed again. To merge the state of an entity into an EntityManager use the EntityManager#merge($entity) method. The state of the passed entity will be merged into a managed copy of this entity and this copy will subsequently be returned.

Example:

<?php
$detachedEntity = unserialize($serializedEntity); // some detached entity
$entity = $em->merge($detachedEntity);
// $entity now refers to the fully managed copy returned by the merge operation.
// The EntityManager $em now manages the persistence of $entity as usual.

When you want to serialize/unserialize entities you have to make all entity properties protected, never private. The reason for this is, if you serialize a class that was a proxy instance before, the private variables won’t be serialized and a PHP Notice is thrown.