【问题标题】:How do I write this Raw Postgres query in sequelize如何在 sequelize 中编写此 Raw Postgres 查询
【发布时间】:2020-09-16 14:28:00
【问题描述】:

我有这个 postgres RAW 查询,我想用 Sequelize 编写它。我该怎么做,因为我对在 Sequelize 中编写具有 JOINS 的查询不太了解。我制作了模型和关联。

这些是模型和关联。

TestParticipant.hasMany(ParticipantHistory, {
    sourceKey: "id",
    foreignKey: "participantId",
    as: "paticipantStatuses"
})

ParticipantHistory.belongsTo(TestParticipant, {
    foreignKey: "participantId",
    as: "paticipantStatuses"
})

这是我想转换为 Sequelize 查询的原始查询

SELECT participant_histories.participant_id,
        participant_histories.created_at,participant_histories.previous_status,
        participant_histories.status,test_participants.test_type_id,test_participants.id,
        test_participants.email,test_participants.scheduled_at,test_participants.valid_till,
        test_participants.is_proctored 
FROM test_participants 
  INNER JOIN participant_histories ON test_participants.id=participant_histories.participant_id 
WHERE user_id='${userId}' 
AND participant_histories.status='${activity}' 
AND participant_histories.created_at>='${isoDate}'

【问题讨论】:

  • 首先创建模型和关联并将它们全部添加到帖子中,以便我们了解participant_historiestest_participants之间的关系。这样我们就可以向您推荐如何将这个原始 SQL 查询转换为 Sequelize 查询
  • 我已经做到了
  • 以上两个表的模型模式在哪里。不知道表之间的关系不会更容易

标签: sql node.js postgresql sequelize.js


【解决方案1】:

因为我在帖子中没有看到模型定义,所以我只建议这样:

// First of all you should correct an alias for TestParticipant like this
ParticipantHistory.belongsTo(TestParticipant, {
    foreignKey: "participantId",
    as: "paticipant"
})

const rows = await ParticipantHistory.findAll({
  raw: true,
  attributes: ['participant_id', 'created_at', 'previous_status', 'status'],
  where: {
    status: activity,
    created_at: {
      [Op.gte]: isoDate
    }
  },
  include: [{
    required: true // this turns into INNER JOIN
    model: TestParticipant,
    attributes: ['test_type_id', 'id', 'email', 'scheduled_at', 'valid_till', 'is_proctored'],
    as: 'participant',
    where: {
      user_id: userId
    }
  }]
})

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2017-06-10
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多