Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
EasonYou opened this issue Aug 28, 2018 · 6 comments
Open

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

EasonYou opened this issue Aug 28, 2018 · 6 comments

Comments

@EasonYou
Copy link

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

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

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

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

@whtiehack
Copy link

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

@EasonYou
Copy link
Author

EasonYou commented Aug 28, 2018

@whtiehack
现在是

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

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

@zhanls
Copy link

zhanls commented Jun 4, 2019

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

@hengshanMWC
Copy link

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

@Lizhooh
Copy link

Lizhooh commented Jul 21, 2019

真是超级小白。

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

@ckvv
Copy link

ckvv commented Dec 28, 2021

封装一个方法

  /**
   * 根据传入的数据生成 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 },
      ]),
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants