【发布时间】: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