繁体   English   中英

如何在Sequelize中使用

[英]How can I do WITH in Sequelize

我有这个查询:

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中进行上述查询?

您可以使用范围来获得相同的效果。 这是一个粗略的示例:

   /* 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: []
        }]
     });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM