如何在 GORM 中建立可选的一对一关系?
我有 2 个对象,ObjectA
和 ObjectB
。
当ObjectA
被创建时,ObjectB
还不存在(并且不能,因为还没有数据)。
一旦创建了ObjectB
,它就需要附加一个相应的ObjectA
(如果存在合适的对象的话)。如果没有合适的 ObjectA
,则新的 ObjectB
根本无法连接到该对象。
因此,所有 ObjectA
实例最终都会附加到 ObjectB
,但并非所有 ObjectB
实例都会有 <代码>对象A。
本质上,我正在寻找 GORM 来构建这样的数据库表:
ObjectA
- Id (NotNull, unique)
- ObjectB_Id[FK: ObjectB.Id] (unique)
ObjectB
- Id (NotNull, unique)
如何将 GORM 域类组合在一起来完成此操作?
我已经尝试了 hasOne、
belongsTo
、原始属性、nullable: true
和 unique: true
约束我能想到,但我必须 缺少一个。这看起来并不是一个特别奇怪的场景,因此必须有某种方法来实现这一点。
I have 2 objects, ObjectA
and ObjectB
.
When ObjectA
gets created, ObjectB
doesn't (and can't, due to not having the data yet) exist yet.
Once ObjectB
is created, it needs to have a corresponding ObjectA
attached to it if an appropriate one exists. If there isn't an appropriate ObjectA
, then the new ObjectB
simply isn't connected to one.
So, all ObjectA
instances will eventually be attached to an ObjectB
, but not all ObjectB
instances will have an ObjectA
.
Essentially, I'm looking for GORM to build database tables like this:
ObjectA
- Id (NotNull, unique)
- ObjectB_Id[FK: ObjectB.Id] (unique)
ObjectB
- Id (NotNull, unique)
How can I put together the GORM domain classes to do this?
I've tried just about every combination of hasOne
, belongsTo
, raw properties, nullable: true
and unique: true
constraints I can think of, but I must be missing one. This doesn't seem like it's a particularly odd scenario, so there must be some way to accomplish this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常情况下,将我的想法组合成一个问题会引导我找到解决方案:
我似乎无法解决的唯一问题是可以将
ObjectB.objectA
设置为已与ObjectB
关联的ObjectA
。当保存新的关联时,GORM 只是不保存该关联。不会引发任何错误,并且从数据库中提取新的ObjectB
会导致其objectA
属性未设置。将
unique: true
添加到ObjectB
类中的objectA
约束也没有帮助。不是默默地失败,而是抛出一个错误,表明由于未设置参数而导致唯一性检查失败。As is often the case, putting my thoughts together into a question lead me to the solution:
The only catch with this that I can't seem to get around is that it's possible to set
ObjectB.objectA
to anObjectA
that is already associated with anObjectB
. When saving the new association, GORM just doesn't save the association. No errors are thrown, and pulling the newObjectB
out of the database leaves it'sobjectA
property unset.Adding
unique: true
to theobjectA
constraints in theObjectB
class doesn't help either. Instead of silently failing, an error is thrown indicating that the uniqueness check is failing due to an un-set parameter.