【发布时间】:2020-10-27 15:34:15
【问题描述】:
我有以下型号:
const Machine = sequelize.define('Machine', { name: DataTypes.STRING });
const Review = sequelize.define('Review', { ReviewDate: DataTypes.DATEONLY });
Review.belongsTo(Machine);
Machine.hasMany(Review);
现在我想获取最后审查日期超过 3 个月的所有机器。
const reviewOverdueDate = new Date();
reviewOverdueDate.setMonth(reviewOverdueDate.getMonth() - 3);
const request = {
include: [{
model: Review,
order: [
["ReviewDate", "DESC"]
],
limit: 1
}],
where: {
// this obviously does not work, because the included Review is an array
// but maybe there is some syntax to access the first entry in that array?
'$Review.ReviewDate$': { [Op.gt]: reviewOverdueDate }
}
Machine.findAndCountAll(request)
如何编写适当的 where 子句来实现目标?有没有办法使用$nested.column$ 语法来访问列表/数组?
我让它在 where 子句中使用 sequelize 文字
where: {
Sequelize.literal(`('${reviewOverdueDate.toISOString()}' > (SELECT "ReviewDate" FROM
"Review" WHERE "Review"."MachineID" = "Machine"."ID" ORDER BY
"Review"."ReviewDate" DESC LIMIT 1))`)
}
但我喜欢用 sequelize 表示法并使用 hasMany 关联。
【问题讨论】:
标签: node.js postgresql sequelize.js associations eager-loading