我的一个实体中有一个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"字段被允许为null,这正是我不希望的。
下面是一些代码,我在其中创建了一个记录,以证明它确实允许引用字段为null值:
$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();
基本上,我不希望许可证在没有分配客户的情况下被持久化。是否需要设置一些注释,或者我应该只要求将客户对象传递给许可证的构造函数?
我使用的数据库引擎是MySQL v5.1,我在Symfony2应用程序中使用Doctrine 2。
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_joincolumn
将nullable = false
添加到JoinColumn
注释:
@ORM'JoinColumn(..., nullable=false)
只是发帖,因为@zim32没有告诉我们应该把声明放在哪里,所以我不得不试错。
Yaml:
manyToOne:
{field}:
targetEntity: {Entity}
joinColumn:
name: {field}
nullable: false
referencedColumnName: {id}
cascade: ['persist']
我找不到如何做到这一点的XML示例,所以我将把这个片段留在这里,以防其他人正在寻找:
<many-to-one field="author" target-entity="User">
<join-column name="author_id" referenced-column-name="id" nullable="false" />
</many-to-one>
名称和引用的列名是必需的,请参阅文档:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/xml-mapping.html#join-列元素