如何正确地保持嵌套的Doctrine实体

时间:2018-02-14 16:07:59

标签: doctrine-orm zend-framework3 persist

我在Zendframework 3中使用Doctrine 2。

我得到一个与OrderAdditions有1:n关系的Order对象,它与OrderItems有1:1的关系。

在订单实体中:

/**
 * @ORM\OneToMany(targetEntity="LwsProject\Entity\OrderAddition", mappedBy="order", cascade={"persist", "remove"})
 */
protected $orderAdditions;

 public function addOrderAdditions($orderAdditions) {
    if($orderAdditions instanceof OrderAddition) {
        $this->orderAdditions->add($orderAdditions);
        $orderAdditions->setOrder($this);
    }else if($orderAdditions instanceof ArrayCollection){
        foreach($orderAdditions as $orderAddition){
            $this->orderAdditions->add($orderAddition);
            $orderAddition->setOrder($this);
        }
    }
    return $this->orderAdditions;
}

public function removeOrderAdditions($orderAdditions) {
    if($orderAdditions instanceof OrderAddition) {
        $this->orderAdditions->removeElement($orderAdditions);
    }else if($orderAdditions instanceof ArrayCollection){
        foreach($orderAdditions as $orderAddition){
            $this->orderAdditions->removeElement($orderAddition);
        }
    }
    return $this->orderAdditions;
}

在OrderAddition中:

/**
 * @ORM\OneToOne(targetEntity="\LwsProject\Entity\OrderItem", cascade={"persist", "remove"}, fetch="EAGER")
 * @ORM\JoinColumn(name="order_item_id", referencedColumnName="id")
 */
protected $orderItem;

在OrderItem中:

/**
 * @ORM\OneToOne(targetEntity="LwsProject\Entity\OrderAddition")
 * @ORM\JoinColumn(name="order_addition_id", referencedColumnName="id")
 */
protected $orderAddition;

我使用新的OrderItem为表单中的多个已发布项创建一个新的OrderAddition。

// $order is either a new Order() or an entity from database.
$orderAddition = new OrderAddition();
//setting Data from post
$orderItem = new OrderItem();
//settign data from post     
$orderAddition->setOrderItem($orderItem);
$orderItem->setOrderAddition($orderAddition);
$order->addOrderAdditions($orderAddition);

当我使用$em->persist($order)使用新订单()时,我正在刷新一切,当我使用数据库中的现有订单时,所有内容都会按预期保持:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'order_item_id' cannot be null

0 个答案:

没有答案