I am using nodejs with Sequelize & PostgreSQL. I have a User table which has 3 relationships with a UserMessagingSystem table:
UserMessagingSystem.belongsTo(User, {
foreignKey: {
name: 'salesperson',
}
});
UserMessagingSystem.belongsTo(User, {
foreignKey: {
name: 'createdBy',
}
});
UserMessagingSystem.belongsTo(User, {
foreignKey: {
name: 'updatedBy',
}
});
User.hasMany(UserMessagingSystem, {
foreignKey: {
name: 'salesperson',
}
});
User.hasMany(UserMessagingSystem, {
foreignKey: {
name: 'createdBy',
}
});
User.hasMany(UserMessagingSystem, {
foreignKey: {
name: 'updatedBy',
}
});
When I do a findOne:
User.findOne({
where: {id: 33},
include: [ { model: UserMessagingSystem }, { model: UserSubscription } ] })
.then(user => {
console.log('user = ');
console.log(user);
I get
id: 33,
...
updatedAt: 2021-01-06T00:27:01.416Z,
userMessagingSystems: [],
userSubscriptions: []
even though when you look in the database itself, there is clearly a row for each.
I have also tried…
User.findOne({
where: {id: 33},
include: [ { model: UserMessagingSystem, where: { salesperson: user.id } }, { model: UserSubscription, where: { salesperson: user.id } } ] })
.then(user => {
console.log('user = ');
console.log(user);
I’m guessing that this is not working because there are 3 “belongsTo” between the two tables. I want the salesperson foreignKey connection, not the other two (createdBy or updatedBy). I’m guessing that Sequelize doesn’t know which I want, and automatically chooses the wrong one, or doesn’t choose at all.
Thank you for your help!