我有这个查询:
WITH tempA AS (SELECT conversationId FROM participant WHERE userId = "aaa"),
tempB AS (SELECT conversationId FROM participant WHERE userId = "bbb")
SELECT conversationId
FROM tempA, tempB
WHERE tempA.conversationId = tempB.conversationId;
查询将返回两个用户参与的对话的 ID。
我在 Sequelize 中也有一个参与模型:
const Participation = sequelize.define("participation", {
//...attributes
});
module.exports = Participation;
如何在不使用 sequelize.query
的情况下在 Sequelize 中执行上述查询?
最佳答案
您可以使用scopes以获得相同的效果。这是一个粗略的例子:
/* for the ON clause of JOIN */
participation.hasMany(participation, {
sourceKey : 'userId',
foreignKey: 'userId',
as: 'selfJoin'
});
participation.addScope('tempA', {
attributes: ['message_id'],
where: {userId: 'aaa'}
});
participation.addScope('tempB',{
attributes: ['message_id'],
where: {userId: 'bbb'}
});
participation.scope('tempB').findAll({
attributes: ['message_id'],
include: [{
model: participation.scope('tempA'),
required: true,
as: 'selfJoin',
attributes: []
}]
});
关于javascript - 我该如何在 Sequelize 中使用WITH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677097/