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();
?
You need to persist them once the relation is already established. Try changing Order::setPackage to the following:
Then establish a relation BEFORE persisting:
The I think you'll find it then works OK. I ran into this exact issue when first playing with Doctrine 2.
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
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.