SwiftiSwift
SwiftiSwift

Reputation: 8777

How to specify foreign key in association query

How can I specify a foreign key, when i make a query that include another model, because i have many foreign keys for that model.

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

UPDATE:

When i have two associations with 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'] }}
]})

Those are my associations :

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' })

Upvotes: 2

Views: 3320

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

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;
};

UPDATE:

Now with your associations:

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' })

Upvotes: 4

Related Questions