简体   繁体   English

Symfony OneToMany Relationship检查插入新的子(Many)实体时是否存在主要(一个)实体

[英]Symfony OneToMany Relationship check if main (One) entity exists if inserting a new child (Many) entity

Whenever I save a new child row, do I have to check if the parent ID actually exists manually? 每当我保存新的子行时,是否必须检查父ID是否确实存在? I would have thought that symfony/doctrine checks automatically and will throw an error b ecause of the OneToMany definition . 我本以为symfony / doctrine会自动检查,并且由于OneToMany定义而将引发错误。

Example: 例:

Main entity ("One"): 主要实体(“一个”):

class Order
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="OrderPayment", mappedBy="orderId")
     */
    private $orderPayments;



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

}

Child Entity ("Many"): 子实体(“许多”):

class OrderPayment
{
    /**
     * @ORM\ManyToOne(targetEntity="Order", inversedBy="orderPayments")
     * @ORM\JoinColumn(name="order_id", referencedColumnName="id")
     */
    private $orderId;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

}

Whenever I insert a new OrderPayment line to the database, shouldn't Symfony check if the $orderId actually exists in the database or do I need to check manually? 每当我在数据库中插入新的OrderPayment行时,Symfony都不应该检查$ orderId是否确实存在于数据库中,还是需要手动检查?

It would be better to rename $orderId to $order . 最好将$orderId重命名为$order Doctrine sees the relations as Entity objects, not as integers. 主义认为这种关系是实体对象,而不是整数。 And yes, if you save the OrderPayment and the Order does not exist, Doctrine will throw an error! 是的,如果您保存OrderPayment且该Order不存在,Doctrine将抛出错误!

When you renamed the properties, regenerated the Entity and updated the db scheme, add an order to an orderpayment like this: 重命名属性,重新生成实体并更新db方案后,将订单添加到orderpay中,如下所示:

$order = // get order from db
$orderPayment = new OrderPayment();
$orderPayment->setOrder($order);
$em->persist($orderPayment);
$em->flush();

You should pass your Order Entity itself into OrderPayment constructor, because OrderPayment can not exist without Order. 您应该将Order Entity本身传递给OrderPayment构造函数,因为如果没有Order,OrderPayment就不会存在。

//OrderPayment
public function __construct(Order $order)
{
    $this->order = $order
    $this-createdAt = \DateTime::now();
}

//Controller or Service
$order = $orderRepository->getOrderBySomeField($field);
if ( ! $order){
    throw new HttpNotFoundException();
}
$orderPayment = new OrderPayment ($order);
$em->persist($orderPayment);
$em->flush;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM