问题描述
一个 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.
这些要求导致 User
的 ManyToOne
关系和 Doctrine 2 中 Package
的 OneToMany
关系.但是 <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;
}
推荐答案
在多对一关系上使用 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!
这篇关于学说 2 不能在 manyToOne 关系中使用 nullable=false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!