【发布时间】:2011-09-02 10:57:53
【问题描述】:
我的一个实体中有一个多对一关系,如下所示:
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”字段允许为空,这正是我不想要的。
这是我创建记录以证明它确实允许引用字段为空值的一些代码:
$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。
【问题讨论】:
-
你有实际创建记录的代码吗?你在用 MySQL 吗?
-
@abe-petrillo 我使用的是 MySQL 5.1。我已使用创建记录的代码示例更新了问题。
-
我自己发现的。根据the doctrine annotation reference,
@Column和@JoinColumn注释有一个nullable选项。将其设置为 false 会导致我想要的行为。
标签: php doctrine-orm relationship many-to-one