sequelize-docs-Zh-CN icon indicating copy to clipboard operation
sequelize-docs-Zh-CN copied to clipboard

如何根据前端给过来的参数判断查询条件

Open EasonYou opened this issue 5 years ago • 6 comments

比如前端传一个为 name 的参数,如果为空,则查询全部,不为空则查询所有

Model.findAll({
  where: {
    name: query.name
  }
})

我该如何判断这里query.name如果为空,就不要有name这个条件? 试过三目运算符置为 undefined,可是出来的查询条件是 where name=null

还是说我只能把where拎出来,用if-else判断来加入条件,再做查询呢

EasonYou avatar Aug 28 '18 08:08 EasonYou

if(!query.name) delete query.name ?

whtiehack avatar Aug 28 '18 08:08 whtiehack

@whtiehack 现在是

const where = {};
if (query.name) {
  Object.assign(where, { name: query.name });
}
Model.findAll({ where })

就是想问是否有更简洁的写法

EasonYou avatar Aug 28 '18 12:08 EasonYou

@EasonYou 最后你是咋写的? 我觉得应该没有比你答案更简单的写法了

zhanls avatar Jun 04 '19 07:06 zhanls

@happyzhanls let name = query.name Object.assign({}, name && {name})

hengshanMWC avatar Jul 08 '19 08:07 hengshanMWC

真是超级小白。

Model.findAll(query.name ? {
    where: {
        name: query.name
    }
} : {});

Lizhooh avatar Jul 21 '19 09:07 Lizhooh

封装一个方法

  /**
   * 根据传入的数据生成 sequelize 的生成语句
   * @param {array} arr data
   * @param {object} options options
   */
  genOpSQL(arr, options = {}) {
    const operators = options.operators || 'and';
    const sequelize = this.app.Sequelize;
    const { Op } = sequelize;
    const sqls = arr.map(val => {
      const { op, field, cast, value } = val;
      if (value === undefined) return {};
      if (!op && !cast) {
        return { [field]: value };
      }
      if (cast) {
        return op ? sequelize.where(
          sequelize.cast(sequelize.col(field), cast),
          { [Op[op]]: this.getOpSQL(op, value) }
        ) : sequelize.where(
          sequelize.cast(sequelize.col(field), cast),
          value
        );
      }
      return {
        [field]: { [ Op[op] ]: this.getOpSQL(op, value) },
      };
    });

    return {
      [Op[operators]]: sqls,
    };
  },

然后这么调用

    const publisherList = await service.app.list({
      where: ctx.genOpSQL([
        { field: 'userId', value: pubId },
        { op: 'in', field: 'id', value: ids },
        { op: 'iLike', field: 'username', value: name },
      ]),
    });

ckvv avatar Dec 28 '21 05:12 ckvv