Sequelize协会备忘单
已针对Sequelize v2 / 3/4/5更新
通常,我认为问题在于我们对创建的表以及关联获得的方法感到困惑。
注意:定义foreignKey或交叉表名称是可选的。Sequelize自动创建它,但是对其进行定义,使编码人员可以读取模型并找出外键/交叉表名称是什么,而不用猜测或需要访问数据库。
TLDR;
O:O
// foreign key has to be defined on both sides.Parent.hasOne(Child, {foreignKey: 'Parent_parentId'})// "Parent_parentId" column will exist in the "belongsTo" table.Child.belongsTo(Parent, {foreignKey: 'Parent_parentId'})O:M
Parent.hasMany(Child, {foreignKey: 'Parent_parentId'})Child.belongsTo(Parent, {foreignKey: 'Parent_parentId'})N:M
Parent.belongsToMany( Child, { // this can be string (model name) or a Sequelize Model Object Class // through is compulsory since v2 through: 'Parent_Child', // GOTCHA // note that this is the Parent's Id, not Child. foreignKey: 'Parent_parentId' })Child.belongsToMany( Parent, { through: 'Parent_Child', // GOTCHA // note that this is the Child's Id, not Parent. foreignKey: 'Child_childId' })为什么要冗长的“ Parent_parentId”,而不仅仅是“
parentId”?这很明显表明它是属于“父母”的外键。在大多数情况下,可以使用更简洁的“ parentId”。*
关联为您提供2种功能:(1)渴望加载和(2)DAO方法:
1.包含(急切加载)
DB.Parent.findOne({ where: { id: 1 }, include: [ DB.Child ]}).then(parent => { // you should get `parent.Child` as an array of children.})2. hasOne(),hasMany()和belongsTo()/ belongsToMany()获得的方法
关联提供了数据访问对象(DAO)方法:
hasOne():
在设置中
Parent.hasOne(Child),可用于
parentDAO实例的方法:
DB.Parent.findOne({ where: { id: 1 } }).then(parent => { // `parent` is the DAO // you can use any of the methods below: parent.getChild parent.setChild parent.addChild parent.createChild parent.removeChild parent.hasChild})#### hasMany():In setting a `Parent.hasMany(Child)`, methods available to `parent` DAO instance:```jsparent.getChildren,parent.setChildren,parent.addChild,parent.addChildren,parent.createChild,parent.removeChild,parent.hasChild,parent.hasChildren归属于()/ belongsToMany:
在设置中
Child.belongsTo(Parent),可用于
childDAO实例的方法:
child.getParent,child.setParent,child.createParent//belongsToManychild.getParents,child.setParents,child.createParents
您也可以有多个关系
亲生父母/子女
// a parent can have many childrenParent.belongsToMany(Child, { as: 'Natural', through: 'Parent_Child', foreignKey: 'Parent_parentId'})// a child must at least have 2 parents (natural mother and father)Child.belongsToMany(Parent, { as: 'Natural', through: 'Parent_Child', foreignKey: 'Child_childId'})养育父母/子女
Parent.belongsToMany(Child, { as: 'Foster', through: 'Parent_Child', foreignKey: 'Parent_parentId'})Child.belongsToMany(Parent, { as: 'Foster', through: 'Parent_Child', foreignKey: 'Child_childId'});上面将
Parent_Child使用
NaturalId和创建交叉表
FosterId。



