57

我的一个实体中有一个 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”字段允许为空,这正是我不想要的。

这是我创建记录以证明它确实允许引用字段为空值的一些代码:

$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。

4

3 回答 3

80

https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_joincolumn

添加nullable = falseJoinColumn注释:

@ORM\JoinColumn(..., nullable=false)
于 2011-05-26T14:23:17.993 回答
5

只是因为@zim32 没有告诉我们应该把声明放在哪里,所以我不得不反复试验。

yaml:

manyToOne:
    {field}:
        targetEntity: {Entity}
        joinColumn:
            name: {field}
            nullable: false
            referencedColumnName: {id}
        cascade: ['persist']
于 2017-12-19T18:28:42.040 回答
3

我找不到如何执行此操作的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-column-element

于 2018-07-23T21:09:49.910 回答