使用 AND 和 OR 子句续集构建动态 where 子句条件
Sequelize build dynamic where clause condition with AND and OR clause
我正在尝试构建一个具有 AND 和 OR 子句的动态续集 where 子句条件。
const objArr = [{ active: 'true' }];
for (let i = 0; i < dynamicList.length; i++) {
objArr.push({
[Op.or]: [{ hierarchy: { [Op.like]: `%${dynamicList[i]}%` } }, { id: dynamicList[i] }],
});
}
const condition = {
where: {
[Op.and]: objArr,
},
attributes: [Sequelize.fn('DISTINCT', Sequelize.col('name'))],
};
db.tableName
.findAll(condition)
.then((resul) => {
callback(null, result);
})
.catch((err) => {
callback(err, null);
});
SQL 已生成查询
SELECT DISTINCT(name)
FROM tableName AS tableName
WHERE (tableName.active = 'true' AND
(tableName.hierarchy LIKE '%111%' OR tableName.id = '111') AND
(tableName.hierarchy LIKE '%222%' OR tableName.id = '222'));
SQL 预期查询 --> active=true AND ((dynamic_list) OR (dynamic_list))
SELECT DISTINCT(name)
FROM tableName AS tableName
WHERE (tableName.active = 'true' AND
(tableName.hierarchy LIKE '%111%' OR tableName.id = '111') OR
(tableName.hierarchy LIKE '%222%' OR tableName.id = '222'));
您需要将所有动态条件组合成一个上层 Op.or
,然后才将此 Op.or
添加到 Op.and
的数组中:
const objArr = [{ active: 'true' }];
const dynamicConditions = [];
for (let i = 0; i < dynamicList.length; i++) {
dynamicConditions.push({
[Op.or]: [{ hierarchy: { [Op.like]: `%${dynamicList[i]}%` } }, { id: dynamicList[i] }],
});
}
if (dynamicConditions.length) {
objArr.push({
[Op.or]: dynamicConditions
});
}
const condition = {
where: {
[Op.and]: objArr,
},
attributes: [Sequelize.fn('DISTINCT', Sequelize.col('name'))],
};
我正在尝试构建一个具有 AND 和 OR 子句的动态续集 where 子句条件。
const objArr = [{ active: 'true' }];
for (let i = 0; i < dynamicList.length; i++) {
objArr.push({
[Op.or]: [{ hierarchy: { [Op.like]: `%${dynamicList[i]}%` } }, { id: dynamicList[i] }],
});
}
const condition = {
where: {
[Op.and]: objArr,
},
attributes: [Sequelize.fn('DISTINCT', Sequelize.col('name'))],
};
db.tableName
.findAll(condition)
.then((resul) => {
callback(null, result);
})
.catch((err) => {
callback(err, null);
});
SQL 已生成查询
SELECT DISTINCT(name)
FROM tableName AS tableName
WHERE (tableName.active = 'true' AND
(tableName.hierarchy LIKE '%111%' OR tableName.id = '111') AND
(tableName.hierarchy LIKE '%222%' OR tableName.id = '222'));
SQL 预期查询 --> active=true AND ((dynamic_list) OR (dynamic_list))
SELECT DISTINCT(name)
FROM tableName AS tableName
WHERE (tableName.active = 'true' AND
(tableName.hierarchy LIKE '%111%' OR tableName.id = '111') OR
(tableName.hierarchy LIKE '%222%' OR tableName.id = '222'));
您需要将所有动态条件组合成一个上层 Op.or
,然后才将此 Op.or
添加到 Op.and
的数组中:
const objArr = [{ active: 'true' }];
const dynamicConditions = [];
for (let i = 0; i < dynamicList.length; i++) {
dynamicConditions.push({
[Op.or]: [{ hierarchy: { [Op.like]: `%${dynamicList[i]}%` } }, { id: dynamicList[i] }],
});
}
if (dynamicConditions.length) {
objArr.push({
[Op.or]: dynamicConditions
});
}
const condition = {
where: {
[Op.and]: objArr,
},
attributes: [Sequelize.fn('DISTINCT', Sequelize.col('name'))],
};