使用表单维护OneToMany链接

时间:2016-10-20 16:06:53

标签: symfony doctrine-orm

想象一下这两个实体

Intervention
    - items        # OneToMany (no cascade)
    addItem()
    removeItem()

Item
    - intervention # ManyToOne

当我执行Intervention时,我想选择相关的Items

我使用Intervention表单,我可以在其中附加/取消附加项目

->add('items', EntityIdType::class, array(
    'class' => Item::class,
    'multiple' => true,
))

提交表单后,我看到Doctrine调用Intervention addItem() removeItem()null

但是当我清空任何以前附加的项目(因此将items作为null发送)时,Doctrine告诉我:

  

属性"项目"也没有其中一种方法" addItem()" /" removeItem()"," setItems()"," items()&# 34;," __ set()"或" __ call()"在课堂上存在并具有公共访问权限#34; AppBundle \ Entity \ Intervention"。

第一个问题是:当我发送setItems()项目列表时,为什么Doctrine找不到我的访问者?

2 个答案:

答案 0 :(得分:0)

我现在的解决方法是实现/** * Set items * * @param $items * * @return Intervention */ public function setItems($items) { foreach ($this->items as $item) { $this->removeItem($item); } if ($items) { foreach ($items as $item) { $this->addItem($item); } } return $this; } 执行添加/删除:

cat-uri

答案 1 :(得分:0)

我认为您需要在ArrayCollection关系的另一面使用ManyToOne。 您的AppBundle\Entity\Item实体类需要:

use AppBundle\Entity\Intervention;
//...

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Intervention", inverseBy="items")
 */
private $intervention;

/**
 * @param Intervention $intervention
 */
public function setIntervention(Intervention $intervention){
    $this->intervention = $intervention;
}

/**
 * @return Intervention
 */
public function getIntervention(){
    return $this->intervention;
}

然后在AppBundle\Entity\Intervention实体类中:

use Doctrine\Common\Collections\ArrayCollection;
//...

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Item", mappedBy="intervention")
 */
private $items;

public function __construct(){
    $this->items = new ArrayCollection();
}

public function getItems(){
    return $this->items;
}

public function setItems($items){
    $this->items = $items;
}