Sequelize - 将此 SQL 查询转换为 Sequelize
Sequelize - convert this SQL query to Sequelize
有什么方法可以将此查询转换为 Sequelize?
SELECT
A1.emp_id, A1.time AS check_in, A2.time AS check_out,
TIMEDIFF(A2.time, A1.time) AS total_time
FROM
hours A1
INNER JOIN
hours A2 ON (A1.emp_id = A2.emp_id
AND DATE(A1.time) = DATE(A2.time))
WHERE
A1.status = 'check_in'
AND A2.status = 'check_out'
ORDER BY
A1.time DESC
谢谢,
谢尔
如果您已经为 hours
定义了一个 Sequelize 模型,那么您还需要定义 hours
和 hours
之间的关联:
Hours.belongsTo(models.Hours, { foreignKey: 'id', as: 'linkedHours' })
然后使用 include
中的 on
选项使用您自己的条件将 hours
与其自身连接,而不是通过 id
:
链接它们
const res = await Hours.findAll({
attributes: ['emp_id', ['time', 'check_in'],
[Sequelize.col('linkedHours.time'), 'check_out'],
[Sequelize.fn('TIMEDIFF', Sequelize.col('linkedHours.time'), Sequelize.col('time')), 'total_time'],
],
where: {
status: 'check_in'
},
include: [{
model: Hours,
as: 'linkedHours',
required: true,
where: {
status: 'check_out'
},
order: [['time', 'DESC']],
on: {
[Op.and]: [
Sequelize.col('hours.emp_id'), '=', Sequelize.col('linkedHours.emp_id'),
Sequelize.fn('DATE', Sequelize.col('hours.time')), '=', Sequelize.fn('DATE', Sequelize.col('linkedHours.time')),
]
}
}]
})
有什么方法可以将此查询转换为 Sequelize?
SELECT
A1.emp_id, A1.time AS check_in, A2.time AS check_out,
TIMEDIFF(A2.time, A1.time) AS total_time
FROM
hours A1
INNER JOIN
hours A2 ON (A1.emp_id = A2.emp_id
AND DATE(A1.time) = DATE(A2.time))
WHERE
A1.status = 'check_in'
AND A2.status = 'check_out'
ORDER BY
A1.time DESC
谢谢, 谢尔
如果您已经为 hours
定义了一个 Sequelize 模型,那么您还需要定义 hours
和 hours
之间的关联:
Hours.belongsTo(models.Hours, { foreignKey: 'id', as: 'linkedHours' })
然后使用 include
中的 on
选项使用您自己的条件将 hours
与其自身连接,而不是通过 id
:
const res = await Hours.findAll({
attributes: ['emp_id', ['time', 'check_in'],
[Sequelize.col('linkedHours.time'), 'check_out'],
[Sequelize.fn('TIMEDIFF', Sequelize.col('linkedHours.time'), Sequelize.col('time')), 'total_time'],
],
where: {
status: 'check_in'
},
include: [{
model: Hours,
as: 'linkedHours',
required: true,
where: {
status: 'check_out'
},
order: [['time', 'DESC']],
on: {
[Op.and]: [
Sequelize.col('hours.emp_id'), '=', Sequelize.col('linkedHours.emp_id'),
Sequelize.fn('DATE', Sequelize.col('hours.time')), '=', Sequelize.fn('DATE', Sequelize.col('linkedHours.time')),
]
}
}]
})