简体   繁体   中英

Is there a way to include an array in a where: $or clause with sequelize?

I have a array of Ids teamsIdsSelected = ['1', '5', .., 'X']

Then, from my table named 'Challenge' I want to get all the the challenges that are linked to each teamId from the array teamsIdsSelected. So far, this is what I tried:

  1. Using this function:
    createWhereClause(column, field) {
        return models.sequelize.where(
            models.sequelize.literal(`${column} in (`),
            `'${field}'`,
            models.sequelize.literal(')'))
    },
  1. Getting the challenges this way:
    const challenges = await Challenge.findAndCountAll({
        where: {
            team_id: createWhereClause(team_id, teamsIdsSelected)
        }
    })

But it doesn't work, I only obtain the challenge with team_id equal to the last item of teamsIdsSelected = teamsIdsSelected.slice(-1)[0] For instance if teamsIdsSelected = ['1', '4', '7'] , the where clause at the end (when I look at the log) is only "where challenge.team_id = 7" .

What I would actually like is an OR condition that would take all challenges that match either 1, 4, or 7 as a team_id. Is there a fast way to do it without creating a for loop ?

Let me know if you need more precision about my issue. Thanks.

const challenges = await Challenge.findAndCountAll({
    where: {
        team_id: { [Op.in]: teamsIdsSelected }
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM