Sequelize ORM中HasOne和BelongsTo的区别 [英] Difference between HasOne and BelongsTo in Sequelize ORM

查看:25
本文介绍了Sequelize ORM中HasOne和BelongsTo的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有 sails.js 应用程序/" rel="noreferrer">续集 ORM.我对何时需要使用 BelongsTo 和 HasOne 感到有些困惑.

I am developing a sails.js app with sequelize ORM. I am a little confused as to when BelongsTo and HasOne need to be used.

文档指出:

BelongsTo 关联是关联的外键源模型上存在一对一关系.

BelongsTo associations are associations where the foreign key for the one-to-one relation exists on the source model.

HasOne 关联是其中的外键的关联目标模型上存在一对一关系.

HasOne associations are associations where the foreign key for the one-to-one relation exists on the target model.

除了指定这些的地方还有其他区别吗?在这两种情况下,行为是否仍然保持不变?

Is there any other difference apart from the the place where these are specified? Does the behavior still continue to be the same in either cases?

推荐答案

这是比较普遍的问题.

主要区别在于语义.你必须决定什么是关系(一些愚蠢的例子):

The main difference is in semantic. you have to decide what is the relationship (Some silly example):

人只有一只右臂.右臂属于一个人.

反过来说有点奇怪:

右臂有个男人.男人属于右臂.

你可以拥有没有右臂的人.但是单靠右臂是没用的.

You can have man without right arm. But alone right arm is useless.

如果 RightArm 和 Man 是模型,在 sequelize 中,它可能看起来像:

In sequelize if RightArm and Man are models, it may looks like:

Man.hasOne(RightArm);      // ManId in RigthArm
RightArm.belongsTo(Man);   // ManId in RigthArm

正如您所注意到的,db 表结构也有所不同:

And as you notice there is also difference in db table structure:

BelongsTo 将在源上添加foreignKey,而hasOne 将在目标上添加(Sequelize 在表'RightArm' 中创建新列'ManId',但不会在'中创建'RightArmId' 列人的桌子).

BelongsTo will add the foreignKey on the source where hasOne will add on the target (Sequelize creates new column 'ManId' in table 'RightArm' , but doesn't create 'RightArmId' column in 'Man' table).

我没有看到更多的差异.

I don't see any more differences.

这篇关于Sequelize ORM中HasOne和BelongsTo的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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