javascript - 将 [op.and] 添加到 Sequelize 查询对象

标签 javascript typescript object sequelize.js javascript-objects

我想根据输入参数组装我的 Sequelize 查询对象。这适用于数据库键,这里有一个例子:

let query = {
  where: {
    id: 5
  }
}

if (inputName) {
  query['where']['name'] = {
    name: inputName
  }
}

Model.findAll(query)
查询输出:
query = {
  where: {
    id: 5,
    name: inputName
  }
}

现在,我想做同样的事情,但将和 [op.and] 添加到查询中:
所需的输出:
query = {
  where: {
    id: 5,
    name: inputName,
    [op.and] = [
      {
        type1: inputType
      },
      {
        type2: inputType
      }
    ]
  }
}
我无法获得以下工作方法:
if (inputType) {
  query['where'][op.and] = [
    {
      type1: inputType
    },
    {
      type2: inputType
    }
  ]
}
感谢有关此主题的任何帮助

最佳答案

这是一个工作示例:

import { sequelize } from '../../db';
import { Model, DataTypes, Op } from 'sequelize';

class User extends Model {}
User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
    },
    name: DataTypes.STRING,
    type1: DataTypes.STRING,
    type2: DataTypes.STRING,
  },
  { sequelize, tableName: 'users', modelName: 'user' },
);

(async function() {
  try {
    await sequelize.sync({ force: true });
    // seed
    await User.bulkCreate([
      { id: 1, name: 'mike', type1: 'a', type2: 'a' },
      { id: 2, name: 'tobias', type1: 'c', type2: 'd' },
    ]);

    // test
    const inputType = 'a';
    const inputName = 'mike';
    const query = { where: { id: 1, name: inputName } };
    if (inputType) {
      query['where'][Op.and] = [{ type1: inputType }, { type2: inputType }];
    }
    const r = await User.findAll(query);
    console.log(r);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();
执行结果:
Executing (default): DROP TABLE IF EXISTS "users" CASCADE;
Executing (default): DROP TABLE IF EXISTS "users" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id"   SERIAL , "name" VARCHAR(255), "type1" VARCHAR(255), "type2" 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 = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "users" ("id","name","type1","type2") VALUES (1,'mike','a','a'),(2,'tobias','c','d') RETURNING *;
Executing (default): SELECT "id", "name", "type1", "type2" FROM "users" AS "user" WHERE ("user"."type1" = 'a' AND "user"."type2" = 'a') AND "user"."id" = 1 AND "user"."name" = 'mike';
[ user {
    dataValues: { id: 1, name: 'mike', type1: 'a', type2: 'a' },
    _previousDataValues: { id: 1, name: 'mike', type1: 'a', type2: 'a' },
    _changed: {},
    _modelOptions:
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Sequelize],
       tableName: 'users',
       hooks: {} },
    _options:
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Array] },
    isNewRecord: false } ]
数据库中的数据记录:
node-sequelize-examples=# select * from users;
 id |  name  | type1 | type2
----+--------+-------+-------
  1 | mike   | a     | a
  2 | tobias | c     | d
(2 rows)

关于javascript - 将 [op.and] 添加到 Sequelize 查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62814975/

相关文章:

javascript - 检查对象参数是否未定义

angular - 如何在下拉列表中将标签设置为空字符串?

php - 使用对象而不是 GET

javascript - Lodash - 在具有默认值的路径处获取值

javascript - chrome.identity.getAuthToken 返回 "bad client id: {0}"错误

javascript - 可拖动范围在附加后不可拖动

javascript - 按特定顺序一个接一个地运行 Gulp 任务

typescript - 如何使用 TypeScript 进行类型化元编程?

typescript - 重复多个函数参数

JavaScript:从 DOM 创建对象