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'
}
)
/*
The above reads:
"Parents" belongs to many "Children", and is recorded in the "Parent_child" table, using "Parents"'s ID.
*/
Child.belongsToMany(
Parent,
{
through: 'Parent_Child',
// GOTCHA
// note that this is the Child's Id, not Parent.
foreignKey: 'Child_childId'
}
)
为什么是详细的“Parent_parentId”而不仅仅是“parentId”?这是为了表明它是属于“Parent”的外键。在大多数情况下,使用更简洁的“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)
,可用的方法parent
DAO 实例:
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():
在设置一个Parent.hasMany(Child)
,可用的方法parent
DAO 实例:
parent.getChildren,
parent.setChildren,
parent.addChild,
parent.addChildren,
parent.createChild,
parent.removeChild,
parent.hasChild,
parent.hasChildren,
belongsTo()/belongsToMany:
在设置一个Child.belongsTo(Parent)
,可用的方法child
DAO 实例:
child.getParent,
child.setParent,
child.createParent,
//belongsToMany
child.getParents,
child.setParents,
child.createParents,
您还可以拥有多种关系
Natural Parents/Children
// a parent can have many children
Parent.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'
})
Foster Parents/Children
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
and FosterId
.