gpt4 book ai didi

javascript - 我该如何在 Sequelize 中使用WITH

转载 作者:行者123 更新时间:2023-12-02 23:50:18 25 4
gpt4 key购买 nike

我有这个查询:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com