Doctrine 2 - 禁止在ManyToOne关系的外键上使用null值

58

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

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();
基本上,我不想让License在没有分配给客户的情况下被持久化。是否需要设置某些注解,或者我只需要求将Customer对象传递给我的License构造函数? 我使用的数据库引擎是MySQL v5.1,并且我正在一个Symfony2应用程序中使用Doctrine 2。

你有实际创建记录的代码吗?你在使用MySQL吗? - Abe Petrillo
@abe-petrillo 我正在使用MySQL 5.1版本。我已经更新了问题,并提供了一个代码示例,其中我创建了一条记录。 - Tobias Gies
2
我自己找到了答案。根据Doctrine注释参考文档@Column@JoinColumn注释中有一个nullable选项。将其设置为false会导致我想要的行为。 - Tobias Gies
3个回答

84

43
@ORM\JoinColumn(nullable=false) - Dmytro
10
使用 yml 格式时,注意在 joinColumn 下添加此属性,而不是关系名称下。我花了很长时间才发现这一点! - achedeuzot
答案中的链接返回“404 Not Found”,需要更新。 - Szymon Sadło
当前文档链接 https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/annotations-reference.html#annref_joincolumn - Phil Rennie

5

我发帖是因为@zim32没有告诉我们应该把语句放在哪里,所以我不得不进行试错。

Yaml:

manyToOne:
    {field}:
        targetEntity: {Entity}
        joinColumn:
            name: {field}
            nullable: false
            referencedColumnName: {id}
        cascade: ['persist']

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接