【发布时间】:2015-08-24 07:13:28
【问题描述】:
有没有办法通过单一方法进行 select 查询和 count_all 查询? 出于分页的目的,我们需要知道项目的总数,以便我们可以计算和显示页数。
【问题讨论】:
有没有办法通过单一方法进行 select 查询和 count_all 查询? 出于分页的目的,我们需要知道项目的总数,以便我们可以计算和显示页数。
【问题讨论】:
getLength: function(req, res) {
Posts.find({}).exec(function(err, items){
return items.length;
});
}
【讨论】:
查看 Sails.Js - How I do pagination in sails.Js 在 Waterline 中的分页。
要获取项目总数,可以使用:
Post.count().exec(function (err, nbOfInstances) {
if(err) return res.negociate(err);
return res.ok(nbOfInstances);
});
【讨论】:
首先查询并获取数据,然后删除限制,跳过参数并获取计数
delete query._criteria.limit;
delete query._criteria.skip;
Model.count(query._criteria).exec(function countCB(error, count) {
});
【讨论】:
我在一个请求中也找不到任何内置方法来执行此操作,所以我这样做:
let queryParams = {},
pageNo = 1,
perPage = 10;
Post.count(queryParams)
.then(_count=>{
return {posts_count: _count,
posts: Post.find(queryParams).paginate({page: pageNo, limit: perPage})};
})
.then(res.ok)
.catch(err=>res.negotiate(err.message));
输出:
/*
{
posts_count: 0,
posts: []
}
*/
【讨论】: