Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize multiple foreign key includes only one column

i have made two foreign keys from user table.

db.Subscription.belongsTo(db.User, {foreignKey: 'creatorId'});
db.Subscription.belongsTo(db.User, {foreignKey: 'subscriberId'});

during search query i get subscriberId column included instead of creatorId

Subscription.findAll({
    where: {
      subscriberId: req.decoded._id
    },
    include: [
      {
          model: User, 
          foreignKey: 'creatorId', 
          attributes: ['name', 'role', 'uid', 'imageUrl']
      }
    ]
})

can someone please find out what i am doing wrong here.

like image 243
yash thakor Avatar asked Aug 02 '17 11:08

yash thakor


1 Answers

Try setting a name for the associations so Sequelize has a better idea which association to include. You can do something like this to set the names on the associations...

db.Subscription.belongsTo(db.User, {
  as: 'creator',
  foreignKey: 'creatorId'
});

db.Subscription.belongsTo(db.User, {
  as: 'subscriber',
  foreignKey: 'subscriberId'
});

Then you can use those names in the query to get the specific association, as so...

Subscription.findAll({
  include: {
    model: User,
    as: 'creator',
    attributes: ['name', 'role', 'uid', 'imageUrl']
  },
  where: {
    subscriberId: req.decoded._identer
  }
});

When you have associations to the same table more than once setting a name helps the ORM determine which association to load. For the record, for all of the records that get returned you can access that association by accessing the .creator on the instance.

Good luck! :)

like image 138
Dylan Aspden Avatar answered Nov 03 '22 23:11

Dylan Aspden