Sequelize配置以检索包含详细信息的总计数

Jam*_*eer 8 database postgresql node.js sequelize.js

我正在使用postgres数据库的节点sequelize.我正在将分页记录加载到我的UI,现在我需要使用我用于检索分页记录的相同查询来获取总记录数.任何人,请提供样本sequelize配置来做同样的事情.请参阅我的预期样本postgres查询以澄清我的问题

SELECT count(*) over() as total ,name FROM students  WHERE gender='male' LIMIT 2 
Run Code Online (Sandbox Code Playgroud)

提前致谢

red*_*off 20

如果要避免指定SQL,也可以使用 findAndCountAll


Adr*_*tti 8

你不能用续集来做到这一点,但你可以通过2个单独的查询来完成,一个用于获取所需的数据,另一个用于获取总数.

第一 :

await Model.findAll({ where: { columnName: condition }});
Run Code Online (Sandbox Code Playgroud)

第二个 :

await Model.count({ where: { columnName: condition }});
Run Code Online (Sandbox Code Playgroud)

如果你想在一个查询中这样做,这可能不是最好的方法(因为你为每个结果添加了一个不是与模型相关的元数据的元数据),你可以创建raw query如下:

await sequelize.query('select count(*) over(), name from table where condition', { model: Model });
Run Code Online (Sandbox Code Playgroud)

我希望我的解释会帮助你:),

祝你今天愉快 !


Yur*_*pka 5

为此,您可以使用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 };
}
Run Code Online (Sandbox Code Playgroud)

params是与对象limitoffset性质重写默认限制和偏移量。

请注意,您可能需要通过distinct: true您和的情况下,include其他车型查询。