HasOne和BelongsTo在SOR序列化ORM中的区别 [英] Difference between HasOne and BelongsTo in Sequelize ORM

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

问题描述

我正在使用 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):

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

相反地说似乎有点奇怪:

Saying it inversely looks a little weird:

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

你可以有没有右臂的男人.但是单独使用右臂是没有用的.

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

如果RightArm和Men是模特,则可能看起来像这样:

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

Man.hasOne(RightArm);
RightArm.belongsTo(Man);

您会注意到,db表结构也有所不同:

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

BelongsTo将在源上添加foreignKey,而hasOne将在目标上添加(Sequelize在表'RightArm'中创建新列'ManId',但不会在'RightArm'表中创建'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).

我再也看不到差异了.

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

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