Trí Phan
Trí Phan

Reputation: 1193

How can I do self join in Sequelize?

I have a Participation Model having two atributes: cid for conversation id and uid for user id.

And I have this query:

SELECT tA.cid
FROM participation tA, participation tB
WHERE tA.uid = "aaa" AND tB.uid = "aab" AND tA.cid = tB.cid;

It will return the id of the conversation in which both users are participating - only the conversation includes both users.

Edited: The Conversation Model and the User Model have the belongs-To-Many association through the Participation Model.

So how can I do the query in Sequelize? Can I use include?

participation.findAll({
  include: [{
    model: participation
  }]

  //Other options...
})

Upvotes: 0

Views: 1920

Answers (1)

Katie Robertson
Katie Robertson

Reputation: 19

An include would be used if you had the IDs joined through a separate model defined with "has many" or "belongs to many" relationship. Then you could try something like:

conversation.findAll({
      where: {
      [Op.and]: [{uid: "aaa"}, {uid: "aab"}]
      include: [{
        model: user,
        through: {
          attributes: ["uid", "cid"]
        }
      }]
    })


Otherwise you could try something like this:

participation.findAll({
  where: {
    [Op.and]: [{uid: "aaa"}, {uid: "aab"}]
  }
});

Upvotes: 1

Related Questions