如何首先设置限制而不是在哪里创建查询?

时间:2019-03-25 02:46:35

标签: node.js sequelize.js

我正在做一些需要搜索的项目。

我尝试一起使用限制和where查询,但是where的优先级高于限制,因此首先它会在哪里进行查询,而不是设置限制,但是我想先设置限制。让limit = 4,所以首先我想从sql中获取4个条目,然后我要在查询中应用

router.post("/****", async function(req, res, err) {
  let limit = 4;
  let searchKeyword = req.body.value;
  let offset = 0;
  let page = (req.body.page && req.body.page) || 1;
  let sortField = req.body.sortField;
  let sortOrder = req.body.sortOrder;
  if (searchKeyword) {
    var searchKey = searchKeyword;
  } else {
    var searchKey = "";
  }
  tblAdmin
    .findAndCountAll()
    .then(data => {
      let pages = Math.ceil(data.count / limit);
      offset = limit * (page - 1);
      tblAdmin
        .findAll({
          attributes: ["id", "firstName", "lastName", "status", "email"],
          limit: limit,
          offset: offset,
          order: [sortfield || "createdAt", sortOrder || "DESC],
          where: {
               firstName: { [Op.like]: "%" + searchKey + "%" } 
          }
        })
        .then(users => {
          res.status(200).json({
            status: 1,
            message: "Data has been retrieved",
            result: users,
            count: data.count,
            pages: pages
          });
        });
    })
    .catch(err => {
      res.status(500).json({
        status: 0,
        message: "Data is not retrieved from database"
      });
    });
});

如果我应用上述逻辑,它会从sql数据中返回与where条件匹配的前四个数据,但是我希望它返回前四个条件在where的结果,而不是第五个

1 个答案:

答案 0 :(得分:0)

findAndCountAll函数保持相同的顺序。第一个函数以不同顺序返回结果,第二个以不同顺序返回。

.then的状态使用等待状态。

router.post("/****", async function (req, res, err) {
    let limit = 4;
    let searchKeyword = req.body.value;
    let offset = 0;
    let page = (req.body.page && req.body.page) || 1;
    let sortField = req.body.sortField;
    let sortOrder = req.body.sortOrder;
    if (searchKeyword) {
        var searchKey = searchKeyword;
    } else {
        var searchKey = "";
    }
    const order = [sortfield || "createdAt", sortOrder || "DESC"];
    offset = limit * (page - 1);
    try {
        let [data, users] = await Promise.all[
            tblAdmin.findAndCountAll({
                order
            }),
            tblAdmin.findAll({
                attributes: ["id", "firstName", "lastName", "status", "email"],
                limit: limit,
                offset: offset,
                order,
                where: {
                    firstName: {
                        [Op.like]: "%" + searchKey + "%"
                    }
                }
            })
        ];
        let pages = Math.ceil(data.count / limit);
        res.status(200).json({
            status: 1,
            message: "Data has been retrieved",
            result: users,
            count: data.count,
            pages: pages
        });
    } catch (error) {
        res.status(500).json({
            status: 0,
            message: "Data is not retrieved from database"
        });
    }
});