Как я могу указать внешний ключ, когда я делаю запрос, включающий другую модель, потому что у меня много внешних ключей для этой модели.
DBTweet.findAll({ where: { userID: followingUserID }, include: [
{ model: DBUser,
include: [
{ model: DBFollower // Here i want to specify the foreign key },
] },
]})
ОБНОВИТЬ:
Когда у меня две ассоциации с as
users is associated to followers multiple times. To identify the correct association, you must use the 'as' keyword to specify the alias of the association you want to include
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' })
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;
};
ОБНОВИТЬ:
Теперь с вашими ассоциациями:
DBUser.hasMany(DBTweet, { as: 'Users', foreignKey: 'userID', onDelete: 'cascade' })
DBTweet.belongsTo(DBUser, { as: 'Users', 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' })
Как говорит ошибка, вам нужно поставить псевдоним на каждую ассоциацию. Чтобы избежать этого, всегда используйте псевдоним.
Если я делаю так: в запросе DBFollower findAll я получаю ту же ошибку. Посмотреть вопрос еще раз
Не могли бы вы обновить ассоциации DBTweet
, DBUser
и DBFollower
Посмотреть вопрос еще раз
Добавьте и псевдоним также на отношение между DBUser
и DBTweet
. Также вы забываете добавить as
ко второму запросу. Смотрите мой пример
Не могли бы вы привести меня в пример. я не знаю что делать
у меня есть две ассоциации hasMany от DBUser до DBFollower с as: я получаю эту ошибку: пользователи связаны с подписчиками несколько раз. Чтобы определить правильную ассоциацию, вы должны использовать ключевое слово as, чтобы указать псевдоним ассоциации, которую вы хотите включить.