sequelize:如果包含的模型的条件匹配,则不包括模型
我想获得今天没有excludeDates的所有RecurringEvents。
我有以下型号:
重复发生的事件
const RecurringEvent = sequelize.definge('recurringEvent,{
id: {type: Sequelize.INTEGER, primaryKey:true},
title: Sequelize.STRING
});
和ExcludeDates使用外键recurringEventId
const ExcludeDate = sequelize.define('exclude_date',{
id: {type: Sequelize.INTEGER, primaryKey:true},
recurringEventId: Sequelize.INTEGER,
date: Sequelize.DATE
});
作为我定义的关系
RecurringEvent.hasMany(ExcludeDate, {foreignKey: 'recurringEventId'});
我可以获得所有的RecurringEvents,包括excludeDates
RecurringEvent.findAll({include:[{model:ExcludeDate}]});
这将给我一个输出,如:
[
{
"id": 1,
"title": "Event1",
"exclude_dates": [
{
"id": 1,
"date": "2019-02-13",
"recurringEventId": 1,
},
{
"id": 2,
"date": "2019-02-14",
"recurringEventId": 1,
}
]
现在我想获得Recurring事件,但前提是今天没有排除日期。
到目前为止我已经尝试过
RecurringEvent.findAll({
include: [{
model: ExcludeDate,
where: {
date: {
[Op.ne]: moment().format('YYYY-MM-DD')
}
}
}]
})
但是这样只会省去当前日期的ExcludeDate条目:
[
{
"id": 1,
"title": "Event1",
"exclude_dates": [
{
"id": 2,
"date": "2019-02-14",
"recurringEventId": 1,
}
]
如何排除整个重复事件,如果它和排除日期设置为今天?
编辑:
我也读过文档
要将包含模型中的where条件从ON条件移动到顶层WHERE,您可以使用'$ nested.column $'
所以我试过这个:
RecurringEvent.findAll({where:{
'$exclude_dates.date$':{
[Op.ne]: moment().format('YYYY-MM-DD')
}
},
include: [{model: ExcludeDate}]
})
但是没有运气,我仍然在没有exclude_dates属性中的一个排除日期的情况下获得RecurringEvents
回答如下:尝试将required: true,
添加到您的包含模型以进行内部连接而不是左连接。例如
RecurringEvent.findAll({
include: [{
model: ExcludeDate,
required: true,
where: {
date: {
[Op.ne]: moment().format('YYYY-MM-DD')
}
}
}]
})