原则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     

要回复问题请先登录注册