Doctrine 2 不能在 manyToOne 关系中使用 nullable=false? [英] Doctrine 2 can't use nullable=false in manyToOne relation?

查看:19
本文介绍了Doctrine 2 不能在 manyToOne 关系中使用 nullable=false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个User 有一个与之关联的Package.许多用户可以参考同一个包.User 不能在没有定义 Package 的情况下存在.User 应该拥有该关系.关系是双向的,因此 Package 中有零个或多个用户.

An User has one Package associated with it. Many users can refer to the same package. User cannot exists without a Package defined. User should own the relation. Relation is bidirectional, so a Package has zero or more users in it.

这些要求导致 UserManyToOne 关系和 Doctrine 2 中 PackageOneToMany 关系.但是 <user 表(即外键)中的 code>package_id 允许 null 值.我试过设置 nullable=false 但命令:

These requirements lead to ManyToOne relation for User and OneToMany relation of Package in Doctrine 2. However package_id in user table (that is foreign-key) allows null values. I've tried setting nullable=false but command:

 php app/console doctrine:generate:entities DL --path="src" --no-backup

表示关系 ManyToOne 没有属性 nullable.我错过了什么?

Says that there is no attribute nullable for the relation ManyToOne. What i'm missing?

class User
{

    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORMManyToOne(targetEntity="Package", inversedBy="users")
     */
    private $package;

}

class Package
{

    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORMOneToMany(targetEntity="User", mappedBy="package")
     */
    private $users;

}

推荐答案

在你的 ManyToOne 关系上使用 JoinColumn 注释:

Use the JoinColumn annotation on your ManyToOne relation:

/**
 * @ORMManyToOne(targetEntity="Package", inversedBy="users")
 * @ORMJoinColumn(name="package_id", referencedColumnName="id", nullable=false)
 */
private $package;

ManyToOne 本身不能为空,因为它与特定列无关.另一方面,JoinColumn 标识数据库中的列.因此,您可以使用普通"属性,例如可为空或唯一!

The ManyToOne itself cannot be nullable, because it doesn't relate to a specific column. The JoinColumn on the other hand identifies the column in the database. Thus, you can use "normal" attributes like nullable or unique!

这篇关于Doctrine 2 不能在 manyToOne 关系中使用 nullable=false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆