belongsToMany 多对多
一个源模型可以连接多个目标模型,目标模型也可以有多个相关的源。
// 表TenderGuarantee的Model中的关联
TenderGuarantee.associate = () => {
TenderGuarantee.belongsToMany(app.mysql.Warrantee, {
as: 'warrantee',
through: 'tender_warrantee',
foreignKey: 'guarantee_id'
});
}
// 表Warrantee的Model中的关联
Warrantee.associate = () => {
Warrantee.belongsToMany(app.mysql.TenderGuarantee, {
as: 'tenderGuarantee',
through: 'tender_warrantee',
foreignKey: 'warrantee_id'
});
}
执行结果: 创建一个新模型tender_warrantee,其包含guarantee_id和warrantee_id两个外键。
as: 对模型重命名
foreignKey: 设置through关系源模型的外键,
otherKey: 设置through关系目标模型的外键。
1. 如果想为连接表(tender_warrantee)添加更多属性,可以建立关联前在sequelize 中为连接表定义一个模型,这会告诉sequelize 使用这个表建立关联而不是创建新表.
module.exports = app => {
const { CHAR, INTEGER, STRING } = app.Sequelize;
const TenderWarrantee = app.mysql.define('tender_warrantee', {
guarantee_id: {
type: INTEGER(11).UNSIGNED,
primaryKey: true,
},
warrantee_id: {
type: INTEGER(11).UNSIGNED,
primaryKey: true,
},
guarantee_file: {
type: STRING,
},
}, {
freezeTableName: true,
timestamps: true,
engine: 'InnoDB',
indexs: [
{
fields: [ 'guarantee_id', 'warrantee_id' ],
unique: true,
},
],
});
TenderWarrantee.associate = () => {
TenderWarrantee.belongsTo(app.mysql.TenderGuarantee, { foreignKey: 'guarantee_id', targetKey: 'guarantee_id' });
TenderWarrantee.belongsTo(app.mysql.Warrantee, { foreignKey: 'warrantee_id', targetKey: 'warrantee_id' });
};
return TenderWarrantee;
};
2. belongsToMany 可以基于through关系查询并可以选择查询属性
TenderGuarantee.findAll({
include: [{
model: warrantee,
through: {
attributes: ['createdAt'],
where: {}
}
}]
});