Doctrine 2 – 在ManyToOne关系的外键上不允许空值

在我的一个实体中有一个ManyToOne关系,如下所示:

class License { // ... /** * Customer who owns the license * * @var \ISE\LicenseManagerBundle\Entity\Customer * @ORM\ManyToOne(targetEntity="Customer", inversedBy="licenses") * @ORM\JoinColumn(name="customer_id", referencedColumnName="id") */ private $customer; // ... } class Customer { // ... /** * Licenses that were at one point generated for the customer * * @var \Doctrine\Common\Collections\ArrayCollection * @ORM\OneToMany(targetEntity="License", mappedBy="customer") */ private $licenses; // ... } 

这将生成一个数据库模式,其中许可证表的“customer_id”字段被允许为空,这正是我不想要的。

下面是一些代码,我创build一个logging来certificate它确实允许参考字段的空值:

 $em = $this->get('doctrine')->getEntityManager(); $license = new License(); // Set some fields - not the reference fields though $license->setValidUntil(new \DateTime("2012-12-31")); $license->setCreatedAt(new \DateTime()); // Persist the object $em->persist($license); $em->flush(); 

基本上,我不希望在没有客户分配的情况下坚持执照。 是否有一些注释需要设置,或者我只需要一个Customer对象传递给我的许可证的构造函数?

我使用的数据库引擎是MySQL v5.1,我在Symfony2应用程序中使用Doctrine 2。