在不破坏我的 Sequelize 代码的情况下,无法将我使用 Op.Like 的查询转换为 Op.Contains

Can't transform my query with Op.Like into Op.Contains without breaking my Sequelize Code

我有以下查询没有问题:

return await this.model.findAndCountAll({
        where: { 
            [`${field}`]: { [Op.like]: `%${params[field]}%` } ,
            mentor: `1`,
            [Op.or]: [
                {
                    city: { [Op.like]: `%${params[localizationField]}%` } ,
                },
                {
                    state: { [Op.like]: `%${params[localizationField]}%` } ,
                }
            ]  
        },
        include: [
            {
                model: MentorCategory,
                include: [
                    {
                        model: Category,
                        where: {
                            name: { [Op.like]: `%${params[categoryField]}%` },
                        },
                    },
                ],
            },  
        ], 
        order: [
            [order, sort]
        ],
        offset: paginate.offset,
        limit: paginate.perPage
    })

但是如果我尝试将 [Op.like] 更改为 [Op.contains](当在 params[categoryField] 中传递多个值时,我需要这个来进行查询,例如 [ 'Em', 'pr' ]) 我收到以下错误:

"Error List: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@> '%Em,pr%' ) ON person.id = mentorCategories.person_id WHERE (person' at line 1"

Op.contains 是 Postgres 专用运算符。

参考:https://sequelize.org/master/manual/model-querying-basics.html#postgres-only-range-operators

不过,我在错误消息中看到您正在使用 MySQL。 对于 MySQL,您可以使用 Op.regexp 代替。

where: {
    name: { [Op.regexp]: `${params[categoryField].join('|'}` }
}

这将生成这样的查询。

... `name` REGEXP 'Em|pr' ...

这将匹配包含“Em”或“pr”的名称。