Doctrine2 ORM Ignore relations in Merge

徘徊边缘 提交于 2019-12-25 02:35:10

问题


I'm implementing a REST Api with FOSRestBundle and I have encountered a problem with the modification of existing entity (PUT)

I have a class Student with has a ManyToOne relation

/**
 * @JMS\MaxDepth(2)
 * @ORM\ManyToOne(targetEntity="ClassRoom", inversedBy="students")
 * @ORM\JoinColumn(name="classroom_id", referencedColumnName="id")
 */
protected $classRoom;

When performing a PUT action I only receive the value attributes since i do not want to let the user modify the relations via a put request. This is a received data example.

{
"id": 3,
"name": "pelayo",
"second_name": "ramon",
"last_name": "fernandez",
"birthday": "1983-08-15T00:00:00+0200"
}

Data gets deserialized with JMS serializer wich sets the $classRoom attribute to null since it didn't find it in the received data.

When performing a merge

$student2 = $this->get('doctrine')->getManager()->merge($student);

If the student2 gets persisted the current relation with classRoom gets erased from the database since the merge sets the relation to null.

This behavior can be dodged by retrieving the current classRoom and setting it to the deserialized entity by hand before the merge, but this is ugly.

Is there any way to tell doctrine to ignore an attribute in a merge from the detached one and make it always use the stored value?


回答1:


Merge is not the only solution.

The JMSSerializerBundle includes an object constructor for Doctrine entities. When you enable this constructor, the deserialized entities are managed entities that can be persisted(with $em->persist($student)). The only attributes modified on the deserialized entity are the ones mentioned in the JSON from the request.

Here is how you can enable it.



来源:https://stackoverflow.com/questions/22379961/doctrine2-orm-ignore-relations-in-merge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!