【问题标题】:Sequelize multiple values in LIKE statement在 LIKE 语句中序列化多个值
【发布时间】:2021-05-04 00:27:42
【问题描述】:

我正在尝试在 Sequelize 中复制此查询:

SELECT * FROM Employee WHERE name LIKE 'john%' or name LIKE 'jane%'

目前,我有这个:

where: {
  name: Sequelize.where(
    Sequelize.fn('LOWER', Sequelize.col(employee.name)),
    'LIKE',
    'john%'
  )
}

但是如何在 Sequelize 中处理多个 LIKE 语句? 我尝试将 Sequelize.where 的第三个参数变成这样的数组:

where: {
  name: Sequelize.where(
    Sequelize.fn('LOWER', Sequelize.col(employee.name)),
    'LIKE',
    ['john%', 'jane%']
  )
}

但我收到此错误: SequelizeDatabaseError: Invalid usage of the option NEXT in the FETCH statement

【问题讨论】:

    标签: sql node.js sequelize.js sql-like


    【解决方案1】:

    这里是一个使用"sequelize": "^5.21.3"的例子:

    import { sequelize } from '../../db';
    import Sequelize, { Model, DataTypes, Op } from 'sequelize';
    
    class Employee extends Model {}
    Employee.init(
      {
        name: DataTypes.STRING,
      },
      { sequelize, modelName: 'Employee' },
    );
    
    (async function test() {
      try {
        await sequelize.sync({ force: true });
        // seed
        await Employee.bulkCreate([{ name: 'james' }, { name: 'JOHN' }, { name: 'JANE' }]);
        // test
        const result = await Employee.findAll({
          where: {
            name: {
              [Op.or]: [
                Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('name')), 'LIKE', 'john%'),
                Sequelize.where(Sequelize.fn('LOWER', Sequelize.col('name')), 'LIKE', 'jane%'),
              ],
            },
          },
          raw: true,
        });
        console.log(result);
      } catch (error) {
        console.log(error);
      } finally {
        await sequelize.close();
      }
    })();
    

    执行结果:

    Executing (default): DROP TABLE IF EXISTS "Employee" CASCADE;
    Executing (default): DROP TABLE IF EXISTS "Employee" CASCADE;
    Executing (default): CREATE TABLE IF NOT EXISTS "Employee" ("id"   SERIAL , "name" VARCHAR(255), PRIMARY KEY ("id"));
    Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'Employee' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
    Executing (default): INSERT INTO "Employee" ("id","name") VALUES (DEFAULT,'james'),(DEFAULT,'JOHN'),(DEFAULT,'JANE') RETURNING *;
    Executing (default): SELECT "id", "name" FROM "Employee" AS "Employee" WHERE (LOWER("name") LIKE 'john%' OR LOWER("name") LIKE 'jane%');
    [ { id: 2, name: 'JOHN' }, { id: 3, name: 'JANE' } ]
    

    数据库中的数据记录:

    =# select * from "Employee";
     id | name
    ----+-------
      1 | james
      2 | JOHN
      3 | JANE
    (3 rows)
    

    【讨论】:

      【解决方案2】:

      回复对您来说已经很晚了,但这可以帮助其他人解决您的问题和我的回答。 :) 您可以简单地传递一个对象数组,例如:

      let employeesName = [{ name: 'james' }, { name: 'JOHN' }, { name: 'JANE' }]);
      
       await Employee.findAll({
            where: {
                [Op.or]: employeesName,
            },
          })
          .then((result) => {
            console.log(result);
           })
           .catch((error) => {
             console.log(error);
           })
      

      【讨论】:

        猜你喜欢
        • 2017-07-26
        • 1970-01-01
        • 2023-03-19
        • 2012-05-05
        • 2019-03-27
        • 2011-08-02
        • 2019-10-25
        • 2020-04-18
        相关资源
        最近更新 更多