我有以下表格:
User
与Event
有1:M的关系
User
与RSVPs
Event
与RSVPs
在提取Event
时,我想要包含RSVPs
,而对于RSVPs
,我想要包含User
。
社团:
用户
tableName: 'Users',
classMethods: {
associate: function (models) {
User.hasMany(models.Event, {
as: 'events',
foreignKey: 'user_id'
})
User.hasMany(models.RSVPs, {
as: 'rsvps',
foreignKey: 'user_id'
})
}
},
事件
tableName: 'Events',
classMethods: {
associate: function (models) {
Event.belongsTo(models.User, {
foreignKey: {
name: 'owner_id',
allowedNull: false,
}
}),
Event.belongsTo(models.User, {
foreignKey: {
name: 'host_id',
allowedNull: true,
}
}),
Event.hasMany(models.RSVPs, {
as: 'rsvps',
foreignKey: 'event_id'
})
}
}
RSVP
tableName: 'RSVPs',
classMethods: {
associate: function (models) {
Rsvp.belongsTo(models.User, {
foreignKey: {
name: 'user_id',
allowedNull: false,
} }),
Rsvp.belongsTo(models.Event, {
foreignKey: {
name: 'event_id',
allowedNull: false,
}
})
}
},
试图获取:
db.Event.findAll({
where: {
id: eventIds
},
order: [['updatedAt', 'ASC']],
limit: pagingLimit + 1,
include: [{
model: db.RSVPs,
as: 'rsvps',
include: [{
model: db.User,
as: 'user_id',
include: [{
model: db.AppCommon,
as: 'app_common'
}],
}]
}, {
model: db.tasks,
as: 'tasks',
}]
}).then(events => {
//Do Something
}
我没有包含来自Tasks
和AppCommon
的关联代码b / c我认为它们并不相关。如果需要,我可以更新问题。
问题:
当我使用上面的Event
代码获取.findAll
时,我收到以下消息:
Express listening on port 3000!
Unhandled rejection Error: User (user_id) is not associated to RSVPs!
我希望获取返回Event
和Task
对象的RSVP
- 在RSVP
个对象中有一个User
对象,并在其中User
对象有一个AppCommon
对象。我做错了什么?
更新
我尝试将查询简化为:
db.RSVPs.findAll({
where: {
user_id: req.user_id
},
include: [{
model: db.User,
as: 'user'
}]
}).then(rsvps => {
)}
社团:
tableName: 'RSVPs',
classMethods: {
associate: function (models) {
Rsvp.belongsTo(models.Event, {
foreignKey: {
name: 'event_id',
allowedNull: false,
}
}),
Rsvp.belongsTo(models.User, {
foreignKey: 'user_id'
})
}
},
但这与#34; Error: User (user) is not associated to RSVPs!
"