如何在Sequelize中使用[Op.or]和[Op.iLike]实现关联模型条件查询
问题描述
基于某解决方案编写的if判断逻辑可正常运行,但需在查询条件中添加以下OR查询规则:
[Op.or]: [ { '$createdBy.name$': { [Op.iLike]: `%${filterCreatedBy}%` } }, { '$createdBy.surname$': { [Op.iLike]: `%${filterCreatedBy}%` } }, ]
当前核心查询代码如下:
Model.findAndCountAll({ where: whereStatement, include: includeArray, attributes: { exclude: excludeArray, }, limit, offset })
尝试的实现方式未成功:
if (filterCreatedBy) { whereStatement['[Op.or]'] = [ { '$createdBy.name$': { [Op.iLike]: `%${filterCreatedBy}%` } }, { '$createdBy.surname$': { [Op.iLike]: `%${filterCreatedBy}%` } }, ] // 关联模型到查询中: includeArray.push({ model: User, as: 'createdBy', attributes: ['id', 'name', 'surname'], }); }
补充:已有可正常运行的Op相关逻辑示例:
if (filterSubject) whereStatement.subject = { [Op.iLike]: `%${filterSubject}%` }; if (filterName) whereStatement.name = { [Op.iLike]: `%${filterName}%` }; if (filterRegion) { whereStatement['$region.name$'] = { [Op.iLike]: filterRegion }; }; if (filterDepartment) { whereStatement['$department.name$'] = { [Op.iLike]: `%${filterDepartment}%` }; };
解决思路
修正Op.or的赋值方式
你之前用字符串'[Op.or]'作为键名是错误的,Op.or是Sequelize提供的Symbol类型常量,必须直接使用whereStatement[Op.or]赋值(前提是已正确导入Op对象)。修改后的代码:if (filterCreatedBy) { whereStatement[Op.or] = [ { '$createdBy.name$': { [Op.iLike]: `%${filterCreatedBy}%` } }, { '$createdBy.surname$': { [Op.iLike]: `%${filterCreatedBy}%` } }, ]; includeArray.push({ model: User, as: 'createdBy', attributes: ['id', 'name', 'surname'], }); }处理多OR条件的合并场景
如果whereStatement中已经存在其他Op.or条件,直接赋值会覆盖原有规则,需要合并数组:if (filterCreatedBy) { const newOrConditions = [ { '$createdBy.name$': { [Op.iLike]: `%${filterCreatedBy}%` } }, { '$createdBy.surname$': { [Op.iLike]: `%${filterCreatedBy}%` } }, ]; whereStatement[Op.or] = whereStatement[Op.or] ? [...whereStatement[Op.or], ...newOrConditions] : newOrConditions; includeArray.push({ model: User, as: 'createdBy', attributes: ['id', 'name', 'surname'], }); }校验关联模型配置
确认User模型与主模型的关联定义中,别名createdBy完全匹配,避免因为别名不一致导致$createdBy.name$无法被Sequelize解析。调试SQL生成
在查询配置中添加logging: console.log,打印生成的SQL语句,直观验证OR条件是否正确生成:Model.findAndCountAll({ where: whereStatement, include: includeArray, attributes: { exclude: excludeArray }, limit, offset, logging: console.log // 打印SQL用于调试 })
内容的提问来源于stack exchange,提问作者DestiX
相关产品推荐
相关产品推荐

