【问题标题】:findAndCountAll count gets a bigger number than the actual returned datafindAndCountAll 计数获得的数字大于实际返回的数据
【发布时间】:2021-01-28 23:00:42
【问题描述】:

我正在使用 Sequelize findAndCountAll() 为我的网站分页。

findAndCountAll() 返回的总项目数(3990)大于实际返回的数据数(3770)。

有谁知道如何使findAndCountAll()返回与返回的实际数据相同的总项目数?

我使用findAndCountAll()查询的表包括另外两个表,如下代码:

const patientModel: IIncludeOptions = {
    model: Patient,
    attributes: ["deviceId", "firstName", "lastName"],
};

const deviceModel: IIncludeOptions = {
    model: Device,
    required: true,
    attributes: ["deviceId", "deviceSerialNumber"],
    include: [patientModel],
};

const eventCodeModel: IIncludeOptions = {
    model: EventCode,
    required: true,
    attributes: ["name"],
};

const opts: IFindOptions = {
    ...pageSizeLimit,
    offset : offsetNum,
    attributes: ["id", "deviceId", "eventId", "dispatchedAt", "message", "createdAt"],
    include: [
        deviceModel,
        eventCodeModel,
    ],
    order: sortBy,
};

const resCount = await DeviceEvent.findAndCountAll(opts).then((response) => {
    const totalItems = response.count;
    return {
        totalItems,
        currentPage: page || 1,
    };
});

【问题讨论】:

  • “实际返回的数据个数(3770)”你怎么算?
  • @Emma findAndCountAll() 方法返回一个数组,其中包含从数据库中获取的所有数据,数组的长度反映了实际返回的数据个数。
  • 如果我没看错,opts 中需要distinct: true,这将计算DeviceEvent 本身的数量(数组长度)。 findAndCountAll() 计算获取的记录数,这意味着如果您有 include,它将计算已连接对象的记录数。

标签: sequelize.js


【解决方案1】:

尝试检查您的 SQL 记录查询。

按照这些说明获取查询转储:How can I see the SQL generated by Sequelize.js?

并查看计数是否与findAndCountAll() 返回给您的相同。

可能sequelize.js 挂载查询的方式会影响结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2019-11-30
    • 1970-01-01
    • 2022-01-27
    • 2012-07-18
    • 2012-01-31
    • 2022-01-22
    相关资源
    最近更新 更多