我应该使用引用还是

我应该使用引用还是

本文介绍了Sequelize - 要定义外键,我应该使用引用还是 belongsTo?或两者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在sequelize中,定义外键有两种方式.

As far as I know, in sequelize, there are two ways to define foreign key.

首先,使用 references 比如:

sequelize.define('foo', {
    bar_id: {
        type: 'blahblah',
        references: {
           model: Bar,
           key: 'id'
        }
    }
});

其次,使用belongsTo方法:

Foo.belongsTo(Bar, { foreignKey: 'bar_id', targetKey: 'id' });

那么当我在模型中定义外键时,我应该使用其中一个吗?还是两者都有?

Then when I define foreign key in a model, should I use one of them? or both?

  • 如果我应该同时使用它们,它们之间有什么区别?
  • 或者如果 belongsTo 足以定义外键,我可以删除 sequelize.define('foo', {...})?
  • If I should use both, what is the difference between them?
  • Or if belongsTo is enough for defining foreign key, can I remove the bar_id definition in sequelize.define('foo', {...})?

推荐答案

根据他们的文档,如果您不想创建关联和约束,可以使用引用创建 FK.否则使用 HasOne、HasMany 或 BelongsTo.

According to their doc, you can create the FK using references if you do not want to create associations and constraints. Otherwise use HasOne, HasMany, or BelongsTo.

http:///docs.sequelizejs.com/manual/tutorial/associations.html#enforcing-a-foreign-key-reference-without-constraints

我个人只使用了 HasOne、HasMany 和 BelongsTo 方法.

Personally I have only used the HasOne, HasMany, and BelongsTo methods.

在上面的链接中查看有关关联的整个部分可能是个好主意.

Probably a good idea to review the entire section on Associations at the above link.

这篇关于Sequelize - 要定义外键,我应该使用引用还是 belongsTo?或两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:13