一开始查百度说是自我关联解决了我试了很多次都不行
其实只要设置别名,查询带上就可以了,这是user和comment表
user.hasMany(models.comment)
comment.belongsTo(models.user, {
foreignKey: 'userId',
targetKey: 'id',
as: 'user'
})
comment.belongsTo(models.user, {
foreignKey: 'toUserId',
targetKey: 'id',
as: 'targetUser'
})
查询
include: [{
model: db.user,
as: 'user',
attributes: {
exclude: ['password']
}
}, {
model: db.user,
as: 'targetUser',
attributes: {
exclude: ['password']
}
}]
ok了
targetUser: Object
text: (...)
toUserId: (...)
updatedAt: (...)
user: Object