Как указать внешний ключ в запросе ассоциации - PullRequest
0 голосов
/ 16 мая 2019

Как мне указать внешний ключ , когда я делаю запрос, включающий другую модель, потому что у меня есть много внешних ключей для этой модели.

DBTweet.findAll({ where: { userID: followingUserID }, include: [
            { model: DBUser, 
        include: [
                { model: DBFollower // Here i want to specify the foreign key },
        ] },
]})

UPDATE:

Когда у меня есть две ассоциации с

пользователей ассоциируется с подписчиками несколько раз. Чтобы определить правильную связь, вы должны использовать ключевое слово «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' })

1 Ответ

1 голос
/ 16 мая 2019
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' })
...