Saving onetoone relation entities

2019-04-02 18:23发布

I'm getting folowwing error, when i try to save my Order Entity:

Integrity constraint violation: 1048 Column 'package_id' cannot be null.

Simplified Entities:

    class Order
    {

        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        protected $id;        

        /** 
         * @ORM\OneToOne(targetEntity="DeliveryPackage",inversedBy="order", cascade={"persist"})  
         * @ORM\JoinColumn  (name="package_id", referencedColumnName="id")   
         */
        protected $package; 

        /**
         * @ORM\ManyToOne(targetEntity="User",cascade={"persist"} )
         * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
         */
        protected $user;

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setPackage($package)
    {
        $this->package = $package;
    }

    public function getPackage()
    {
        return $this->package;
    }
}

class DeliveryPackage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /** 
     * @ORM\OneToOne(targetEntity="Order",mappedBy="deliverypackage",cascade={"persist"})
     * @ORM\JoinColumn  (name="order_id", referencedColumnName="id")       
     */
    protected $order;    

    public function setId( $id )
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setOrder( $order )
    {
        $this->order = $order;
    }

    public function getOrder()
    {
        return $this->order;
    }   

}

The main point, is that both of entities are new. So they dont have id's yet. Is there any option, to save both of them with

$em->persist( $order );
$em->flush();

?

2条回答
老娘就宠你
2楼-- · 2019-04-02 19:07

You need to persist them once the relation is already established. Try changing Order::setPackage to the following:

public function setPackage($package)
{
    $this->package = $package;
    $package->setOrder($this);
}

Then establish a relation BEFORE persisting:

$order = new Order();
$package = new Package();
$order->setPackage($package);
$em->persist($order);
$em->flush();

The I think you'll find it then works OK. I ran into this exact issue when first playing with Doctrine 2.

查看更多
在下西门庆
3楼-- · 2019-04-02 19:26

Solution is partly based on the previous answer, but it still not enough to complitely solve the problem.

So there were 2 action to do. First - add

$package->setOrder($this);

to my setter.

Second - you can't define both referencing columns as strictly not NULL. So, i've redefined package_id coulmn as null, and it worked out.

查看更多
登录 后发表回答