如何解决原则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 \”字段被允许为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();
基本上,我不希望在没有分配客户的情况下永久保留许可证。是否需要设置一些注释,或者我是否只需要将Customer对象传递给我的License的构造函数?
我使用的数据库引擎是MySQL v5.1,并且我在Symfony2应用程序中使用了Doctrine 2。
解决方法
https://www.doctrine-project.org/projects/doctrine-orm/zh/2.6/reference/annotations-reference.html#annref_joincolumn
在
JoinColumn
注释中添加nullable = false
:
@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>
名称和referenced-column-name是必需的,请参阅文档:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/xml-mapping.html#join-column-element
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。