例如,我有以下两个类(为简洁起见省略了 getter / setter),它们在映射中以两种方式链接:
class Form
{
private $elements = array();
public function addElement($element)
{
$this->elements[] = $element
$element->setForm($this);
}
}
class Element
{
private $form;
private $name;
}
<one-to-many field="elements" target-entity="Element" mapped-by="form"/>
<many-to-one field="form" target-entity="Form" inversed-by="elements">
<join-column name="formId" referenced-column-name="id" on-delete="CASCADE" on-update="CASCADE"/>
</many-to-one>
如果我执行以下操作;向表单添加两个元素,但只保留一个元素,我想要发生的是实体管理器完全忽略未持久化的元素,而将另一个元素和表单插入数据库:
$form = new Form;
$em->persist($form);
$element = new Element;
$element->setName('firstName');
$form->addElement($element);
$em->persist($element);
$element2 = new Element;
$element2->setName('lastName');
$form->addElement($element2);
$em->flush();
目前得到以下错误:
exception 'Doctrine\ORM\ORMInvalidArgumentException' with message 'A new entity was found through the relationship 'Form#elements' that was not configured to cascade persist operations for entity Element@0000000019217f52000000009c20d747. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'Element#__toString()' to get a clue
据我所知,没有级联选项可以忽略新实体(http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive- persistence-cascade-operations)并使用 preUpdate 生命周期回调从 $elements 数组中删除违规实体也不起作用,因为在运行回调之前引发了异常。
有没有办法解决这个问题?