使用连接 table 对 where 范围进行续集
Sequelize where scope with an joined table
我有一个属于许多关系和一个加入 table
courseTree.associate = function (models) {
models.courses.belongsToMany(models.courses, {
through: 'course_tree',
as: 'children',
foreignKey: 'parent_id',
otherKey: 'child_id'
});
};
目前,当我 运行 找到我的所有课程时,即使是儿童课程,这是预期的行为,但我希望有另一个范围,我可以只请求儿童课程。
在我的范围内,我有以下位置:
scopes: {
parents: {
where: {
children: { [Op.not] : null }
}
}
}
但是其余的 Api 给了我以下输出
"name": "GeneralError",
"message": "column courses.children does not exist",
"code": 500
在文档中我找不到任何方法来执行此操作,我尝试了 sequelize.literal 和 in 运算符但没有成功。有谁知道这是怎么做到的,我确定我错过了什么。
使用 Sequelize.literal
解决了这个问题
courses.addScope('getParents', {
where: {
[Op.and]: Sequelize.literal('"courses"."id" NOT IN (SELECT "course_tree"."child_id" FROM "course_tree")')
}
})
我 运行 遇到的另一个问题是子模型与父模型相同,在这种情况下 where 也应用于子模型。我通过在 include.
中添加 where: false
解决了这个问题
我有一个属于许多关系和一个加入 table
courseTree.associate = function (models) {
models.courses.belongsToMany(models.courses, {
through: 'course_tree',
as: 'children',
foreignKey: 'parent_id',
otherKey: 'child_id'
});
};
目前,当我 运行 找到我的所有课程时,即使是儿童课程,这是预期的行为,但我希望有另一个范围,我可以只请求儿童课程。
在我的范围内,我有以下位置:
scopes: {
parents: {
where: {
children: { [Op.not] : null }
}
}
}
但是其余的 Api 给了我以下输出
"name": "GeneralError",
"message": "column courses.children does not exist",
"code": 500
在文档中我找不到任何方法来执行此操作,我尝试了 sequelize.literal 和 in 运算符但没有成功。有谁知道这是怎么做到的,我确定我错过了什么。
使用 Sequelize.literal
courses.addScope('getParents', {
where: {
[Op.and]: Sequelize.literal('"courses"."id" NOT IN (SELECT "course_tree"."child_id" FROM "course_tree")')
}
})
我 运行 遇到的另一个问题是子模型与父模型相同,在这种情况下 where 也应用于子模型。我通过在 include.
中添加where: false
解决了这个问题