我有消息模型和消息接收者模型,我想对创建的message和messageRecipient实例进行一些处理,但是当我尝试在afterCreate Hook中获取嵌套模型(例如message.getMessageRecipients)时,我看到的却是空数组进入数据库中已创建的数据,则可以成功创建message和messageRecipient。
模型创建
const message = {
subject : 'test',
// some more fields
MessageRecipients: [
{
userId: 123
}
]
}
models.Message.create(message, {
include : [models.MessageRecipient]
})
挂钩
models.Message.hook('afterCreate', function (_message) {
return _message.getMessageRecipients()
.then((recipients)=>{
// need to do some processing but recipients are empty
})
})
关系
Message.hasMany(models.MessageRecipient, {
foreignKey: 'messageId',
onDelete : 'CASCADE'
})
MessageRecipient.belongsTo(models.Message, {
foreignKey: 'messageId',
onDelete : 'CASCADE'
})