首页 > 解决方案 > 不使用 Sequelize 方法的 Sequelize 查询中的分页

问题描述

我使用 sequelize 查询加入了两个表,但无法获取分页数据。我已经看到很多例子在 sequelize 方法中只添加了限制和偏移量。但由于我没有使用这些方法并且我的 Games 表没有模型,我不得不使用原始查询来加入我的表。我的分页查询和代码如下:

exports.fetchPlayers = (req, res) => {
const { page, size } = req.query;
  const { limit, offset } = getPagination(page, size);
    db.sequelize.query('SELECT * FROM matches JOIN public."Games" ON (matches.match_id = public."Games".id) ORDER BY public."Games".id DESC', 
    {type: db.sequelize.QueryTypes.SELECT,
      limit: limit, 
      offset: offset // this is how I have added limit and offset
    })
  .then(function(matchDetails) {
    const response = getPagingData(matchDetails, page, limit);
      res.json({
          matchPlayer: response
      });
  }).catch(err => {
    res.json({status: 'failed', message: err});
}); 
};

const getPagination = (page, size) => {
const limit = size ? +size : 1;
  const offset = page ? page * limit : 0;
  return { limit, offset };
};
const getPagingData = (data, page, limit) => {
  const totalItems = data.length;
  const matches = data;
  const currentPage = page ? +page : 0;
  const totalPages = Math.ceil(totalItems / limit);

  return { totalItems, matches, totalPages, currentPage };
};

这段代码给了我数据库中的所有数据。任何人都可以帮助我吗?谢谢。

标签: mysqlnode.jsexpresspaginationsequelize.js

解决方案


您需要执行以下操作。

将您的原始查询修改为

SELECT * FROM matches JOIN public."Games" ON (matches.match_id = public."Games".id) ORDER BY public."Games".id DESC LIMIT page*size, size;

example: SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

同样在续集中,

在替换中传递页面和大小,例如

..
sequelize.query('SELECT * FROM matches JOIN public."Games" ON (matches.match_id = public."Games".id) ORDER BY public."Games".id DESC LIMIT :page * :size, :size', {
replacements: {
 page: page,
 size: size
},
type: 'SELECT'
})
..
  1. 要获取可用的总页数,您需要使用完全相同的连接和 where 条件再次调用数据库并获取计数。您可以通过除以页面大小的计数来确定总页数。

推荐阅读