I have a custom attribute in my sequelize query and it returns correctly, but I cannot figure out how to map it to the object.
The broad idea is to get all users with their relationship to the logged user.
The query goes like this:
db.user.findAll({
include: [
{model: db.friend, as: 'from_user', required: false, where:{ to_user_id: logged_user_id } },
{model: db.friend, as: 'to_user', required: false, where:{ from_user_id: logged_user_id } },
],
attributes: { include: [[
db.sequelize.literal(
`CASE
WHEN 'to_user.status' = 'accepted' OR 'from_user.status' = 'accepted' THEN 'friend'
WHEN 'to_user.status' = 'new' THEN 'i_invited'
WHEN 'from_user.status' = 'new' THEN 'he_invited'
ELSE 'stranger'
END`
),
'relationship'
]]},
The attribute that is returned, but not mapped is of course relationship.
const user = sequelize.define<IUserInstance, IUserAttributes>('user', {
id: {
type: dataTypes.STRING,
allowNull: false,
unique: true,
defaultValue: () => generate(),
},
//some other fields...
}, {
classMethods: {
associate: (models) => {
user.hasOne(models.friend, {
foreignKey: 'from_user_id',
constraints: false,
as: 'from_user',
});
user.hasOne(models.friend, {
foreignKey: 'to_user_id',
constraints: false,
as: 'to_user',
});
}
},
timestamps: true,
paranoid: true,
underscored: true,
});
Of course IUserInstance and IUserAttributes have a relationship defined in them.
How do I ensure that the relationship is mapped to IUserAttributes?
via MichaĆ K
No comments:
Post a Comment