Serginho
Serginho

Reputation: 7490

JMSserializer deserialize related Doctrine Entity

I have json like this:

"relatedCollection": [
  {
     id:1,
     name: "something",
     country: {
           id:1
          }
  },
    {
     id:2,
     name: "something 2",
     country: {
           id:1
          }
  }

]

Two related items that have a common country that exists in database. If I deserialize with JMSserializer, and it creates a two different instances of COUNTRY entity.

When you apply merge with doctrine, set properly country to "something", but not to "something 2". So the result after save is:

"relatedCollection": [
  {
     id:1,
     name: "something",
     country: {
           id:1
          }
  },
    {
     id:2,
     name: "something 2",
     country: null
  }

]

For Doctrine there are two different entities called Country that are detached. And doctrine attach the first and save it properly but not the second.

This only happens with relations ManyToOne, when you merge a collection with the same related entity id. If you save country 1 and country 2, there'is no repeated country, so save property.

Any solution?

Upvotes: 1

Views: 1157

Answers (1)

ScayTrase
ScayTrase

Reputation: 1830

JMS Serializer just does the object deserialization, it does not handles the doctrine object for you.

You have to do any kind of merge, cascade merge, for example

http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations

You can write a deserialization Listener\Subscriber to do auto-merge for you automatically

Upvotes: 1

Related Questions