Doctrine orm Doctrine2中的逆关联赋值
Doctrine2是否支持在关联从相反方向更改时更新关联?如果不是开箱即用,是否有插件/扩展我可以用来涵盖这种行为 以下是我的一个例子:Doctrine orm Doctrine2中的逆关联赋值,doctrine-orm,Doctrine Orm,Doctrine2是否支持在关联从相反方向更改时更新关联?如果不是开箱即用,是否有插件/扩展我可以用来涵盖这种行为 以下是我的一个例子: Organization /** * @Id * @Column(type="integer") */ protected $id /** * @ManyToOne(targetEntity="Organization", inversedBy="children", cascade={"persist"}) * @JoinColumn(n
Organization
/**
* @Id
* @Column(type="integer")
*/
protected $id
/**
* @ManyToOne(targetEntity="Organization", inversedBy="children", cascade={"persist"})
* @JoinColumn(name="parent_org_id", referencedColumnName="id")
*/
protected $parent;
/**
* @OneToMany(targetEntity="Organization", mappedBy="parent", cascade={"persist"})
*/
protected $children;
不会。条令2通过拥有方跟踪关联,由于它试图对实体的行为产生最小的影响,所以它不想添加这种功能 跟踪反向侧的更改的标准方法是,通过向实体添加逻辑,在反向侧进行更改时更新所属侧,确保它们保持同步 在您的示例中,可以使用addChild、removeChild和setParent函数执行以下操作:
public function addChild(Organization $child)
{
$this->children[] = $child;
$child->setParent($this); // < update the owning side
}
public function removeChild(Organization $child)
{
$this->children->removeElement($child);
$child->setParent(null); // < update the owning side
}
public function setParent(Organization $parent = null)
{
$this->parent = $parent;
}
除了增加的复杂性之外,当例如将大量子对象从一个父对象移动到另一个父对象时,此方案并不理想,因为removeChild需要线性时间,从而为移动创建了O(n^2)运行时间
public function addChild(Organization $child)
{
$this->children[] = $child;
// safely update the owning side
if ($child->getParent() != $this) {
$child->setParent($this);
}
}
public function removeChild(Organization $child)
{
$this->children->removeElement($child);
// safely update the owning side
if ($child->getParent() == $this) {
$child->setParent(null);
}
}
public function setParent(Organization $parent = null)
{
$oldParent = $this->parent;
$this->parent = $parent;
// update the inverse side
if ($oldParent) {
$oldParent->removeChild($this); // will not call setParent
}
if ($this->parent) {
$this->parent->addChild($this); // will not call setParent
}
}