I am having problems recreating the following query in Sequelize. I have been sitting for hours trying to figure this out.
I am using camelCase instead of snake_case so I cannot reuse the same query.
The query does not work if I exchange all snake_cased variables to camelCase in the query. I get back "relation \"directmessages\" does not exist". I cannot access the directmessages table in psql with TABLE directmessages; - but I know its supposed to be there.
I can also not figure out how to do the same query with sequelize.
Basically I need to fetch every User the current user has already direct messaged with. Either as a sender or receiver.
models.sequelize.query(
'select distinct on (u.id) u.id, u.username from users as u join direct_messages as dm on (u.id = dm.sender_id) or (u.id = dm.receiver_id) where (:currentUserId = dm.sender_id or :currentUserId = dm.receiver_id) and dm.team_id = :teamId',
{
replacements: { currentUserId: user.id, teamId: id },
model: models.User,
raw: true,
},
These are the relevant models for this query:
User Model:
User.associate = (models) => {
User.belongsToMany(models.Team, {
through: models.Member,
foreignKey: 'userId',
})
User.belongsToMany(models.Channel, {
through: 'channel_member',
foreignKey: 'userId',
})
}
DirectMessage Model:
DirectMessage.associate = (models) => {
DirectMessage.belongsTo(models.Team, {
foreignKey: 'teamId',
})
DirectMessage.belongsTo(models.User, {
foreignKey: 'receiverId',
})
DirectMessage.belongsTo(models.User, {
foreignKey: 'senderId',
})
}
I tried creating the query with sequelize like this:
models.User.findAll({
include:[{
model: models.DirectMessage,
where: {
teamId,
[models.sequelize.Op.or]: [{senderId: user.id}, {receiverId: user.id}]
}
}]
}, { raw: true })
I get back "message": "directMessage is not associated to user!", which I presume is because DirectMessage is associated to User, but not the other way around.
Does anybody have any tips of how I can reconstruct this query?