当我进行包含另一个模型的查询时,如何指定外键,因为我对该模型有很多外键。
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' })
答案 0 :(得分:1)
fatal: unable to access 'https://username@bitbucket.org/repo/smodels.git/': The requested URL returned error: 403
更新:
现在与您的关联:
DBTweet.findAll({
where: { userID: followingUserID },
include: [{
model: DBUser,
as: 'Users', //here goes the alias as well
include: [{
model: DBFollower,
as: 'Followers' //here is goes the alias of the association
}],
}]
});
module.exports = (sequelize, DataTypes) => {
const DBUser = sequelize.define('DBUser', {
// your attributes
});
DBUser.associate = (models) => {
DBUser.hasMany(models.DBFollower, { as: 'Followers', foreignKey: 'your_key' });
// DBUser.belongsTo(models.DBFollower, { as: 'Followers', foreignKey: 'branch_id' });
};
return DBUser;
};