问题
I have this function duplicateCourseAction whose goal is to ... duplicate a Course object
public function duplicateCourseAction(Request $request) {
if ($this->getRequest()->isXmlHttpRequest() == false) {
return new Response("Bad request", 405);
}
$em = $this->getDoctrine()->getManager();
$parameters = $request->request->all();
$course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
$duplicate = clone $course;
$duplicate->setDate(new \DateTime($parameters['date']));
$em->persist($duplicate);
$em->flush();
return new Response("200");
}
According to documentations, "clone" keyword make a surface copy (ie. a reference copy). This is clearly not what I want because my Course entity contains many relations to others entities, I would rather want a values copy.
I discovered the unserialize(serialize(object)) trick :
public function duplicateCourseAction(Request $request) {
if ($this->getRequest()->isXmlHttpRequest() == false) {
return new Response("Bad request", 405);
}
$em = $this->getDoctrine()->getManager();
$parameters = $request->request->all();
$course = $em->getRepository('EntTimeBundle:Course')->findOneById($parameters['id']);
$duplicate = unserialize(serialize($course));
$duplicate->setDate(new \DateTime($parameters['date']));
$em->persist($duplicate);
$em->flush();
return new Response("200");
}
But I have this error with Doctrine :
Notice: Undefined index: 000000003ed2e9ea00000000ee270fde in /home/mart_q/Diderot/ent/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2776
回答1:
You can control what exactly gets cloned by overriding the __clone()
method in your Course
entity. You can set id
to null
and clone referenced objects if you need a deep copy.
The serialization/unserialization feels like a hack, so I recommend against using it.
回答2:
Trick here is that you must unset duplicate entity id. Otherwise breaks the logic of the doctrine. Doctrine has some known limitations. Also check this question, its very similar.
来源:https://stackoverflow.com/questions/18592872/deep-cloning-an-object-clone-vs-serialize