簡體   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