当我进行包含另一个模型的查询时,如何指定外键,因为我有许多该模型的外键。
DBTweet.findAll({ where: { userID: followingUserID }, include: [
{ model: DBUser,
include: [
{ model: DBFollower // Here i want to specify the foreign key },
] },
]})
更新:
当我与 as 有两个关联时
用户多次与关注者相关联。要识别正确的关联,您必须使用“as”关键字来指定要包含的关联的别名
DBFollower.findAll({ where: { followerUserID: req.params.userID }, include: [
{ model: DBUser, attributes: { exclude: ['email', 'password', 'loginType', 'telephoneNumber'] }}
]})
这些是我的协会:
DBUser.hasMany(DBTweet, { foreignKey: 'userID' }, { onDelete: 'cascade' })
DBTweet.belongsTo(DBUser, {foreignKey: 'userID'}, { onDelete: 'cascade' })
DBUser.hasMany(DBFollower, { as: 'followingUserIDAlias', foreignKey: 'followingUserID' }, { onDelete: 'cascade' })
DBFollower.belongsTo(DBUser, { as: 'followingUserIDAlias', foreignKey: 'followingUserID' }, { onDelete: 'cascade' })
DBUser.hasMany(DBFollower, { as: 'followerUserIDAlias', foreignKey: 'followerUserID' }, { onDelete: 'cascade' })
DBFollower.belongsTo(DBUser, { as: 'followerUserIDAlias', foreignKey: 'followerUserID' }, { onDelete: 'cascade' })
青春有我
相关分类