【问题标题】:Sequelize configuration to retrieve total count with detailsSequelize 配置以检索带有详细信息的总数
【发布时间】:2018-05-12 19:26:50
【问题描述】:
我正在使用带有 postgres 数据库的节点 sequelize。
我正在将分页记录加载到我的 UI,现在我需要使用用于检索分页记录的相同查询来获取总记录数。
任何人,请提供示例 sequelize 配置以执行相同操作。
请查看我预期的示例 postgres 查询以澄清我的问题
SELECT count(*) over() as total ,name FROM students WHERE gender='male' LIMIT 2
提前致谢
【问题讨论】:
标签:
node.js
database
postgresql
sequelize.js
【解决方案1】:
你不能用 sequelize 做到这一点,但你可以通过 2 个单独的查询来完成,一个用来获取你需要的数据,另一个用来获取总数。
第一个:
await Model.findAll({ where: { columnName: condition }});
第二个:
await Model.count({ where: { columnName: condition }});
如果您想在一个查询中执行此操作,这可能不是最好的方法(因为您为每个结果添加了与模型无关的元数据),您可以像这样创建一个 raw query:
await sequelize.query('select count(*) over(), name from table where condition', { model: Model });
希望我的解释对你有所帮助:),
祝你有美好的一天!
【解决方案3】:
您可以为此使用findAndCountAll。
findAndCountAll - 在数据库中搜索多个元素,返回数据和总数
这是一个例子:
const getStudents = async params => {
const { count, rows: students } = await Student.findAndCountAll({
where: {
gender: 'male',
},
limit: DEFAULT_PAGE_SIZE,
order: [['id', 'ASC']],
...params,
});
return { count, students };
}
params 是具有覆盖默认限制和偏移量的limit 和offset 属性的对象。
请注意,您可能还需要传递distinct: true,以防您在查询中include 其他模型。
【解决方案4】:
您可以通过两种方式统计数据
- 有数据 (findAndCountAll)
- 没有数据 (count)
1: 有数据
const students = await students.findAndCountAll({
where: {
gender = "male"
}
});
console.log(students)
它将返回 gender 为男性的 Count 个学生以及该学生的数据
2: 无数据
const students = await students.count({
where: {
gender = "male"
}
});
console.log(students)
它将仅返回 gender 为男性的 Count 学生