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