mysql - 不使用 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 };
};
这段代码给了我数据库中的所有数据。任何人都可以帮助我吗?谢谢。
解决方案
您需要执行以下操作。
将您的原始查询修改为
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'
})
..
- 要获取可用的总页数,您需要使用完全相同的连接和 where 条件再次调用数据库并获取计数。您可以通过除以页面大小的计数来确定总页数。
推荐阅读
- javascript - CodePen:在 div [CSS] 中格式化列表文本时遇到问题
- security - 如何在 Tapestry-security 上启用 rememberme
- vba - 从数据分支设置切片器并打印 PDF
- amazon-web-services - 新对象的 Amazon S3 一致性模型
- python - 如何合并字符串熊猫df
- html - 如何覆盖默认的 IOS 下拉菜单?
- c# - 在添加到列表之前存在检查之间的性能并且在 linq 中存在差异
- java - 对线程应用程序进行单元测试
- javascript - 如何使用来自外部 API 的数据播种 mongodb?
- adonis.js - SyntaxError: Unexpected identifier - 尝试使用 AdonisJS 播种数据时收到