簡體   English   中英

如何使用 sequilize 在 where 子句中添加“或”語句

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

我想為同一行創建多個 Where / OR 子句:這是我的請求正文

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

    ]

這是我的 javascript 代碼

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

預期產生的查詢:

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

給我的問題:

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

我是否需要在代碼中添加一些東西才能將 AND 轉換為 OR? 我還有一些其他可能的“和”查詢,所以我只想在這個查詢上使用“或”

您需要使用Op.or運算符。 更多信息,請參閱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[];
}

例如

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();
  }
})();

執行結果:

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 } ]

檢查數據庫:

node-sequelize-examples=# select * from subcategories;
 category_id
-------------
           1
           2
           3
(3 rows)
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 })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM