Persistent Doctrine objects with associations that were deserialized using the JMSSerializer

After successfully deserializing the json string in Entity Entity with associations. When perseverance, the Doctrine defines these associations as "new entities" always. How can I update associations only with an identifier and not change the values ​​of related entities if there are any changes?

My case:

I have several database tables with static data. The easiest to store units. (I have a doctrine object called Unit). The table looks like this:

|id|name |ratio | |1 |mgr |1 | |2 |gr |1000 | |3 |Kgr |1000000| 

The user can then create an element that also has a server-side doctrine object called Unit. I use the client-side backbone.js model, and when it is updated, it is sent to my Symfony2 application as follows:

 //Item object to be serialized into Item entity { id: 13141 weight: 100 unit: { id:1 name:mgr ratio:1 } //many more attributes here } 

Now I deserialize with the JMSSerializer, everything is fine, but I want the doctrine to update only the module identifier of this relationship, and not the entire block.

When I persist, the doctrine complains and tells me that it has found a “new unit” (which is not what I want), and tells me to cascade persist in Entity Entity. But if I do this and someone modifies unit json, won't that change my static Units table?

For example: A bad user modifies Json by sending this:

 //BAD item object to be serialized into Item entity { id: 13141 weight: 100 unit: { id:1 name:BadName //Will this get persisted to the database? ratio:1 } //many more attributes here } 

Of course, I do not want this to happen. I just want to add Unit with id: 1 to the element.

This case is simple, and I could just extract the device by identifier and then set it in essence, but in my real application the Item object is much larger, so I want to process it automatically.

¿Any ideas?

+6
source share
1 answer

Let me understand this:

When you deserialize text, what type of element element? Is this class instance just an array ?

If I understand correctly and this is an instance of class , you can set cascade to merge (not persist ) in the unit property so that you can:

 $em = ...; // your entity manager $item = $em->merge($item); // merge will cascade to `unit` property as well 

Hope this helps ...

+4
source

Source: https://habr.com/ru/post/950109/


All Articles