Sequelize: Query same join table with different conditions

五迷三道 提交于 2019-12-05 20:29:57

When writing more complicated join queries in sequelize, I usually end up using the raw query interface. It looks a bit complicated, but hopefully it makes sense:

  • Select the Threads and join with the ThreadContact table
  • Group by Thread.id
  • Aggregate the group using array_agg on the contact ids. So we now have an array of all associated contacts for each thread.
  • Then filter to where the aggregated array 'contains' (as represented by @>) your inputted filter. See postgres array functions.

The result will be all Threads which are associated with at least those 4 contacts.

sequelize.query(`
  SELECT Thread.*
  FROM Thread
  INNER JOIN ThreadContact
    ON Thread.id = ThreadContact.threadId
  GROUP BY Thread.id
  HAVING array_agg(ThreadContact.contactId) @> ARRAY[:contactIds];
`, {
  model: Thread,
  mapToModel: true,
  type: sequelize.QueryTypes.SELECT,
  replacements: {contactIds: [1, 2, 3, 4]},
});

Also note that the column names may be incorrect from how your model is defined, I just made some assumptions on how they would look.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!