How to add “or” statement in the where clause using sequilize

旧城冷巷雨未停 提交于 2020-04-30 06:39:16

问题


I want to make multiple Where / OR clauses for the same row: This is my request body

"sub_categories":[
        {
            "category_id":2
        },
        {
            "category_id":1
        }

    ]

This is my javascript code

var where = []
if (subcategories != undefined && subcategories.length) {
    subcategories.forEach(async (item) => {
        where.push({
            '$subcategories.id$': item.id
        })
    });
}

Expected query to produce :

SELECT * FROM TABLE where ( sub_categories .category_id = 1 OR sub_categories .category_id = 2)

Questy that is given to me :

SELECT * FROM TABLE where sub_categories .category_id = 2 AND sub_categories .category_id = 2)

Do I need to add something to the code in order to transform that AND into a OR? Also I have some other possible "And" querys , so I just wanted to use the "Or" on this one


回答1:


You need to use Op.or operator. More info, see https://sequelize.org/v5/manual/querying.html

/** Example: `[Op.or]: [{a: 5}, {a: 6}]` becomes `(a = 5 OR a = 6)` */
export interface OrOperator {
  [Op.or]: WhereOptions | WhereOptions[] | WhereValue | WhereValue[];
}

E.g.

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

class SubCategory extends Model {}
SubCategory.init(
  {
    category_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
    },
  },
  { sequelize, modelName: 'SubCategory', tableName: 'subcategories' },
);

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // seed
    await SubCategory.bulkCreate([{}, {}, {}]);
    // test
    const whereValue: WhereValue[] = [];
    const subcategories = [{ category_id: 2 }, { category_id: 1 }];
    subcategories.forEach((item) => {
      whereValue.push({ category_id: item.category_id });
    });
    const result = await SubCategory.findAll({
      where: {
        [Op.or]: whereValue,
      },
      raw: true,
    });
    console.log(result);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

Execution results:

Executing (default): DROP TABLE IF EXISTS "subcategories" CASCADE;
Executing (default): DROP TABLE IF EXISTS "subcategories" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "subcategories" ("category_id"   SERIAL , PRIMARY KEY ("category_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 = 'subcategories' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "subcategories" ("category_id") VALUES (DEFAULT),(DEFAULT),(DEFAULT) RETURNING *;
Executing (default): SELECT "category_id" FROM "subcategories" AS "SubCategory" WHERE ("SubCategory"."category_id" = 2 OR "SubCategory"."category_id" = 1);
[ { category_id: 1 }, { category_id: 2 } ]

Check the database:

node-sequelize-examples=# select * from subcategories;
 category_id
-------------
           1
           2
           3
(3 rows)



回答2:


var where = {}
if (subcategories != undefined && subcategories.length) {
   where['$or'] = []
    subcategories.forEach((item) => {
        where['$or'].push({
           '$subcategories.id$': item.category_id
        })
    });
}
...
const result = await db.someModel.findAll({ where })


来源:https://stackoverflow.com/questions/61311414/how-to-add-or-statement-in-the-where-clause-using-sequilize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!