sql - 如何在 sequelize 中编写此 Raw Postgres 查询
问题描述
我有这个 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}'
解决方案
因为我在帖子中没有看到模型定义,所以我只建议这样的东西:
// 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
}
}]
})
推荐阅读
- sqlalchemy - SQLAlchemy - SQL Server TCP 提供程序的 Microsoft ODBC 驱动程序 17:错误代码 0x68 (104) (SQLExecDirectW)
- nativescript - 在“@nativescript/core”中找不到“fileSystemModule”
- excel - 从公式VBA复制值,得到零
- paypal - 卖家的Paypal Onboard,生成的注册链接的奇怪行为
- java - 使用 Heroku Scheduler 运行一个简单的 Java HelloWorld
- wordpress - 在 wodfpress 的 RSS 提要中显示修改日期
- batch-file - 批处理文件:同时启动两个进程,然后在进程 2 完成后终止进程 1
- javascript - 时间流分页不适用于nodejs
- cakephp - 如何将普通查询转换为 cakephp 标准
- google-apps-script - 从另一个单元格中减去一个单元格中的值的脚本