本文介绍了Doctrine2 ORM忽略合并关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用FOSRestBundle实现一个REST Api,而且我已经遇到了修改现有实体(PUT)的问题。



我有一个类Student ManyToOne关系

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

执行PUT操作时,我只接收值属性,因为我不想让用户修改通过put请求的关系。
这是收到的数据示例。

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

数据使用JMS序列化器反序列化,将$ classRoom属性设置为null,因为它没有在收到的数据中找到它。



执行合并时

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

如果student2被持久化,与classRoom的当前关系将从数据库中删除,因为合并设置关系为空。



此行为可以通过检索当前的classRoom并在合并之前手动将其设置为反序列化实体,但这是丑陋的。

有没有办法告诉学说从分离的合并中忽略一个属性,并使它总是使用存储的值?

解决方案

合并不是唯一的解决方案。



JMSSerializerBundle包含Doctrine实体的对象构造函数。当您启用此构造函数时,反序列化实体是可以持久化的管理实体(使用 $ em-> persist($ student))。在反序列化实体上修改的唯一属性是请求中JSON中提到的属性。



是如何启用它的。


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?

解决方案

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.

这篇关于Doctrine2 ORM忽略合并关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:33