Tengo dos modelos; giftModel y userGiftModel. Están relacionados entre sí de la siguiente manera:
userGiftModel.belongsTo(giftModel, { as: "gift", foreignKey: "giftId"}); giftModel.hasMany(userGiftModel, { as: "userGifts", foreignKey: "giftId"});Cuento la cantidad de obsequios para el usuario actual como userGiftCount y mi objetivo es devolver un estado determinado por userGiftCount.
Aquí está mi consulta y el problema es que el estado siempre devuelve 1.
const gifts = await models.giftModel.findAll({ include: { model: models.userGiftModel, as: 'userGifts', where: { userId: req.user.id }, required: false }, where: { giftStatus: 1, [Op.and]: [ { [Op.or]: [ { giftStartDate : { [Op.lt] : moment().unix() } }, { giftStartDate : null } ], }, { [Op.or] : [ { giftEndDate : { [Op.gt] : moment().unix() } }, { giftEndDate : null } ], } ] }, attributes: [ ['giftId', 'id'], ['giftName', 'name'], ['giftDescription', 'description'], ['giftAmount', 'amount'], ['giftLink', 'link'], ['giftStartDate', 'startDate'], ['giftEndDate', 'endDate'], ['giftReportCount', 'reportCount'], ['giftReportSum', 'reportSum'], [fn("COUNT", col("userGifts.giftId")), "userGiftCount"], //here is my main problem [literal(`CASE WHEN 'userGiftCount' <> 0 THEN 0 ELSE 1 END`), 'status'] ], order: [ ['giftId', 'desc'] ], group: ['giftId'], includeIgnoreAttributes: false, })