[英]Doctrine2 strictly trying to inser t NULL when i use one-to-one and many-to-one relations
Places.yml
manyToOne:
excursions:
targetEntity: Excursions
inversedBy: places
inverse: true
cascade: ["ALL"]
nullable: false
joinColumn:
name: idx
referencedColumnName: place_id
Excursions.yml
oneToOne:
places:
targetEntity: Places
mappedBy: excursions
游览有一个place_id。 所以$exccursion->getPlaces()
只返回一行。
现在,当我尝试向Places
表插入一个值时,Doctrine2表示Not null violation: 7 ERROR: null value in column "idx" violates not-null constraint
我不知道为什么会这样。 如果我删除manyToOne
然后插入工作。 但这次getPlaces()
无效。
UPDATE
问题是,我使用mappedBy对数据库。 我应该这样做:
Places.yml
manyToOne:
--remove--
Excursions.yml
oneToOne:
places:
targetEntity: Places
joinColumn:
name: place_id
referencedColumnName: idx
这解决了这个问题。 但我通过随机尝试/玩耍找到了这个。 所以,我不知道为什么:)任何人都知道请explain
我。
首先,映射是不正确的。 您不应该在ManyToOne
中Places.yml
,并且反转的一侧在Excursions.yml
映射为OneToOne
。 这很可能是您遇到这些错误的原因。
你还想要一个Excursion
将一个Places
对象链接到它,但如果我理解你的问题,则Places
可以有更多的Excursions
对象。 所以你的映射应该是这样的:
# Places.yml
OneToMany:
excursions:
tagertEntity: Excursions
mappedBy: places
和
# Excursions.yml
ManyToOne:
places:
targetEntity: Places
inversedBy: excursions
joinColumn:
name: places_id
referencedColumnName: id
注意:
ManyToOne
关系应该在只有另一个的实体内部 OneToMany
关系应该在具有另一个对象的实体内部 joinColumn: name:
应具有要在数据库中创建的列的名称 joinColumn: referencedColumnName:
应该包含您要用于映射关系的目标实体的字段(我建议您使用id,因为它是唯一的) 创建此映射后,运行以下命令:
php app/console doctrine:generate:entities BUNDLE_PREFIX
如果BUNDLE_PREFIX
将是您的捆绑名称的第一部分。 这将生成所有正确的getter和setter。 不要忘记更新数据库模式:
php app/console doctrine:schema:update --force
正如我推荐的最后一些建议(除非你打算这样做)你将实体名称更改为Excursion
和Place
因为每个对象应该只保留1个地方或游览。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.