Question

I have an entity object with properties id and trucknr. I place a few data and then query for all. I use JMS SerializerBundle to serialize this to JSON and I'm using file_put_contents to export that to a JSON file, then I use deserialize to read my JSON file, and it deserializes fine. I use:

$read = $serializer->deserialize($file,'ArrayCollection<App\TestBundle\Entity\Truck>','json');

The problem is when I'm trying to persist this to my database. For that I used:

$em = $this->getDoctrine()->getManager();
$em->merge($read);
$em->flush();

I get this error:

EntityManager#merge() expects parameter 1 to be an entity object, array given. 

when I run dump_var on $read I get an array collection of three rows:

array(3) { [0]=> object(App\TestBundle\Entity\Truck)#767 (2) { ["id":protected]=> NULL ["trucks_nr":protected]=> string(4) "1243" } 
[1]=> object(App\TestBundle\Entity\Truck)#782 (2) { ["id":protected]=> NULL ["trucks_nr":protected]=> string(4) "3245" } 
[2]=> object(App\TestBundle\Entity\Truck)#783 (2) { ["id":protected]=> NULL ["trucks_nr":protected]=> string(4) "5622" } }

I don't know if what I'm trying to do is possible. When I'm querying for one row it persists or merges fine. Is it possible to persist an array collection of objects, and, if so, how?

Was it helpful?

Solution

You deserialize an array of entities which you need to loop through so they can be merged properly:

$em = $this->getDoctrine()->getManager();
for ($i = count($read) -1; $i >= 0; $i--) {
    $em->merge($read[$i]);
}
$em->flush();

[edit] Not sure if you really want to use merge() as your deserialized entities don't seem to be detached but rather new ones (as they've got no id)? In this case you need to call persist() instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top