Sequelize - 在条件
的情况下关联表列我想在续集模型中执行此查询:
SELECT * FROM `model_game` AS `Game` INNER JOIN `model_activity` AS `Activity` ON `Game`.`ActivityId` = `Activity`.`id` WHERE `Game`.`startAt` > ('2017-03-25 07:37:36'-`Activity.duration`) AND `Game`.`status` = 'NotStarted';
我尝试过使用sequelize.col()函数,但仍然无法对其进行poulate。我的代码在
之下My Game model . table name model_game
var Game = sequelize.define("Game", {
startAt: DataTypes.DATE,
status: DataTypes.ENUM('NotStarted','Completed')
}, {
classMethods: {
associate: function(models) {
Activity.belongsTo(models.Activity);
}
}
});
我的活动模型,表名称model_activity
var Activity = sequelize.define("Activity", {
title: DataTypes.STRING,
duration: DataTypes.INTEGER
},{
classMethods: {
associate: function(models) {
Activity.hasMany(models.Game);
}
}
});
查询查询,现在返回值,但是sequelize.col(" Activity.duration")根本没有效果
var currentTime = moment();
models.Game.findAndCountAll({
where: { status: 'NotStarted',
startAt: {gt: currentTime.subtract(moment.duration(sequelize.col("Activity.duration"), 'minutes'))},
},
include: [{
model: models.Activity
}]
}).then(function(result) {
//Success
});
但是上面的代码没有填充" Activity.duration"持续时间值。并且没有错误,应该采取什么措施来纠正这个问题。在此先感谢
答案 0 :(得分:1)
您可以尝试将DATE_SUB()
功能与sequelize.literal
结合使用。
models.Game.findAndCountAll({
where: {
status: 'NotStarted',
startAt: {
$gt: models.sequelize.fn(
'DATE_SUB',
models.sequelize.literal('NOW()'),
models.sequelize.literal('INTERVAL Activity.duration MINUTE')
)
}
},
include: [models.Activity]
}).then(result => {
// result...
});
上面的代码会生成类似下面的查询:
SELECT * FROM games INNER JOIN activities
ON games.activityId = activities.id
WHERE games.status = 'NotStarted'
AND games.startAt > DATE_SUB(NOW(), INTERVAL activities.duration MINUTE);
根据您要获取的代码和查询,我使用NOW()
作为您要从中减去Activity.duration
字段的日期。此外,我使用了MINUTE
间隔,但您可以根据Activity.duration
字段代表的内容(小时,分钟,秒等)更改它。