需要帮助构建一个奇怪的 Sequelize 查询

Need help building an odd Sequelize query

一些上下文:

我有两个 table:challengesparticipants

challenges table 列:iduserIdname.

participants table 列:iduserIdchallengeId

challenge table 上的 userId 列表示挑战的所有权。

participants table 只是一个关联 table,用于跟踪已加入挑战的用户。

challenges.hasMany(participants)

participants.belongsTo(challenges)

挑战的所有者可能是也可能不是参与者。


我的问题:

我如何构造单个 Sequelize 查询来查找特定用户所有拥有或加入的挑战?

示例数据:

challenges
+----+--------+-------------+
| id | userId |    name     |
+----+--------+-------------+
|  1 |   2001 | Challenge 1 |
|  2 |   2002 | Challenge 2 |
+----+--------+-------------+

participants
+----+--------+-------------+
| id | userId | challengeId |
+----+--------+-------------+
|  1 |   2001 |           1 |
|  2 |   2002 |           1 |
+----+--------+-------------+

查找用户 2002 的所有拥有或加入挑战的期望结果:

challenges: [
  {
    id: 1,
    userId: 2001,
    name: "Challenge 1"
  },
  {
    id: 2,
    userId: 2002,
    name: "Challenge 2"
  }
]

试一试:

SELECT challenges.* 
FROM      challenges 
LEFT JOIN participants 
       ON challenges.id = participants.challengeId 
WHERE challenges.userId   = 2002 
   OR participants.userId = 2002;