背景:
在我的应用程序中,我有一个具有自引用 ManyToOne
关联的实体(许多孩子可以指向一个单亲)。而且我有一项功能可以使用 Doctrine ORM 一次对许多实体进行大规模更新。为了防止由于加载了许多实体而导致性能急剧下降,Idetach
实体一旦被更新。
问题:
当我detach
一个有孩子的实体后来尝试更新这些孩子中的任何一个时, Doctrine 抱怨它不再认识父母。即使我在尝试更新子实体之前是merge
父实体。
问题:
分离父实体时我做错了什么?我已经尝试在父列上执行 cascade="merge" 和/或“分离”,当我尝试坚持时,Doctrine 仍然抱怨父级是一个未知实体。
我已经模拟了一个简单的例子来重现这一点。见下文。
测试代码:
实体\事物.php
/**
* @ORM\Entity()
* @ORM\Table(name="things")
*/
class Thing
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Thing", inversedBy="children", cascade={"detach","merge"})
* @ORM\JoinColumn(name="parentId", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
/**
* @ORM\OneToMany(targetEntity="Thing", mappedBy="parent")
*/
protected $children;
/**
* @ORM\Column(type="string", length=64)
*/
protected $name;
public function __construct($name = null)
{
$this->children = new ArrayCollection();
$this->name = $name;
}
// .. SNIP ...
}
测试动作:
public function testThingAction($_route)
{
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('AcmeThingBundle:Thing');
// simple setup of a couple things in the DB
$t1 = $repo->findByName('Thing1');
if (!$t1) {
$t1 = new Thing('Thing1');
$t2 = new Thing('Thing2');
$t2->setParent($t1);
$em->persist($t1);
$em->persist($t2);
$em->flush();
return $this->redirect($this->generateUrl($_route));
}
list($t1, $t2) = $repo->findAll();
// detach and re-merge Thing1
// This should cause Thing1 to be removed and then re-added
// to the doctrine's known entities; but it doesn't!?
$em->detach($t1);
$em->merge($t1);
// try to update T2
$t2->setName('Thing2 - ' . time());
$em->persist($t2);
// will fail with:
// A new entity was found through the relationship Thing#parent
$em->flush();
return array();
}