【问题标题】:Pagination in Sequelize query without using Sequelize method不使用 Sequelize 方法的 Sequelize 查询中的分页
【发布时间】:2021-07-07 07:25:15
【问题描述】:

我使用 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 };
};

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

【问题讨论】:

    标签: mysql node.js express pagination sequelize.js


    【解决方案1】:

    您需要执行以下操作。

    将原始查询修改为

    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 条件再次调用数据库并获取计数。您可以通过除以页面大小的计数来确定总页数。

    【讨论】:

    • 我收到此错误使用单独的 LIMIT 和 OFFSET 子句。
    • 从查询选项中删除限制和偏移量。
    猜你喜欢
    • 2017-03-23
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2016-12-02
    • 2014-10-24
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多