我有belongsTo
这样的关系:
classMethods: {
associate: function(models) {
User.belongsTo(models.Prefs, {timestamps: false, foreignKey: 'Type', targetKey: 'UserType'})
}
}
产生
LEFT OUTER JOIN `prefs` AS `Prefs` ON `User`.`Type` = `Prefs`.`UserType`
问题是我还需要添加额外的检查,如
AND `Prefs`.`Section` = 'GLOBAL'
有可能吗?
答案 0 :(得分:1)
我认为这与Sequelize - Join with multiple column 重复。
您需要在ON
子句
JOIN
条件
User.findAll({
include: [
{
model: Prefs,
on: {
Type: db.sequelize.where(db.sequelize.col("User.Type"), "=", db.sequelize.col("Prefs.UserType")),
Section: 'GLOBAL'
},
attributes: [] // do not return any columns of Prefs table
}
]
}).then((users) => {
// resulting users...
});
修改强>
我相信scope
正是您所寻找的。尝试将其添加到关联
classMethods: {
associate: function(models) {
User.belongsTo(
models.Prefs,
{
timestamps: false,
foreignKey: 'Type',
targetKey: 'UserType',
scope: { Section: 'GLOBAL' }
}
);
}
}