sequelize multiple foreign key includes only one column
10,241
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! :)
Author by
Admin
Updated on June 11, 2022Comments
-
Admin almost 2 years
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 ofcreatorId
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.