[英]Doctrine ORM default value of none existing entity
Lets say we have entities which are named Element
, those MAY belong to a entity called Layout
.假设我们有名为
Element
实体,这些实体可能属于一个名为Layout
的实体。 Elements and Layouts have a ManyToOne
relation, where Many Elements belong to one Layout
. Elements 和 Layouts 具有
ManyToOne
关系,其中 Many Elements 属于一个Layout
。
The databas engine used is MySQL, additionally we use a unique key, which the layout_id
is a part of.使用的数据库引擎是 MySQL,另外我们使用唯一键,
layout_id
是其中的一部分。 So therefore we have in the Elements
table, a column called layout_id
which can not be null
(because of the composite unique key), and has a default of 0
.因此,我们在
Elements
表中有一个名为layout_id
的列,它不能为null
(因为复合唯一键),并且默认值为0
。 The value of 0
is a magic value and treated as 'No Layout assigned' throughout the code base (there are no FK's between Element
and Layout
because of this).值
0
是一个魔法值,在整个代码库中被视为“未分配布局”(因此, Element
和Layout
之间没有 FK)。
The problem with Doctrine ORM is that it tries to load a Layout with a ID of 0
, which it can not find because it does not exists. Doctrine ORM 的问题在于它试图加载一个 ID 为
0
的布局,但它无法找到,因为它不存在。 We can not create a Layout
entry with ID 0
because Layouts
have other foreign keys and there own other constraints.我们无法创建 ID 为
0
的Layout
条目,因为Layouts
具有其他外键并且有其他约束。
Is there any suggestion on how to overcome this.有没有关于如何克服这个问题的建议。 Basically when the
layout_id
in the Element
is 0
, we would like not to load a Layout
.基本上当
Element
的layout_id
为0
,我们不想加载Layout
。
In such case you cannot set this layout_id
as part of the composite key.在这种情况下,您不能将此
layout_id
设置为组合键的一部分。 This is because of the foreign key constraint.这是因为外键约束。 Either your
layout_id
has to be nullable
(meaning it cannot be part of the composite key) or you have to make a row in your layout
table with id 0 (so it can be used as an identifier).您的
layout_id
必须可以为nullable
(意味着它不能成为组合键的一部分),或者您必须在layout
表中使用 id 0 创建一行(因此它可以用作标识符)。
A solution could be to not use a composite key but instead add a primary key column for uniquely identifying your entity (surrogate key).一个解决方案可能是不使用复合键,而是添加一个主键列来唯一标识您的实体(代理键)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.