gpt4 book ai didi

node.js - 如何在 sequelize 查询中编写这个 Where 子句?

转载 作者:行者123 更新时间:2023-12-03 22:38:21 25 4
gpt4 key购买 nike

我有一个 SQL Server SELECT 查询,我想将它转换为 Sequelize 查询生成器:

SELECT ...
FROM usertbl as user
WHERE
[user].[is_deleted] = 0
AND [user].[id_role] = 6
AND ( LOWER([user].[cardid_print]) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].code) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].[firstname]) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].lastname) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].fullnameEN) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].firstname) LIKE CONCAT('%', query_string, '%')
OR LOWER([user].idnumber) LIKE CONCAT('%', query_string, '%')
OR CONCAT(LOWER([user].lastname), ' ', LOWER([user].firstname)) LIKE CONCAT('%', query_string, '%')
)

如何将其转换为 sequelize 查询选项对象,如下所示:
{
where: {
is_deleted: 0,
...
}
}

或者像这样:
{
where: sequelize.where(sequelize.fn('FUNCTION',
sequelize.col('field')), 'value')
}

编辑1:
  • 查询字符串可以为空,如果查询字符串为空或空字符串,则去掉 where 条件

  • 编辑2:
  • id_role 可以为空,如 query_string

  • 编辑3:
  • 我发现这种方式没有调用 LOWER/UPPER 函数 here
  • 我已经测试了这段代码,它已经完成了!

  • 感谢您的回答@ChuongTran

    最佳答案

    你可以试试吗?并让我知道:)

    var sequelize = require('sequelize');
    var query_string = 'something..';
    var id_role = 6;
    var query = {
    is_deleted: 0
    }
    if(id_role !== undefined){
    query['id_role'] = id_role;
    }
    if(query_string !== undefined || query_string.length <= 0){
    query['$or'] = sequelize.literal(`( LOWER(cardid_print) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(code) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(firstname) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(lastname) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(fullnameEN) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(firstname) LIKE CONCAT('%', ${query_string}, '%')
    OR LOWER(idnumber) LIKE CONCAT('%', ${query_string}, '%')
    OR CONCAT(LOWER(lastname), ' ', LOWER(firstname)) LIKE CONCAT('%', ${query_string}, '%')
    )`);
    }
    User.findAll({
    where: query
    })
    .then(users => {

    })
    .catch(err => {
    console.log('err', err);
    });

    关于node.js - 如何在 sequelize 查询中编写这个 Where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094358/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com