提问人:z0mbieKale 提问时间:11/10/2023 更新时间:11/10/2023 访问量:36
Sequelize count 或 findAndCountAll 返回无效结果
Sequelize count or findAndCountAll return invalid result
问:
尝试在添加 include -> where 语句时对父表中的行进行计数。两者并返回无效的结果。count()
findAndCountAll()
对于患者 ID 7h95Aj1P
,我在数据库中只有一种治疗,而总治疗是 49
使用 findAndCountAll
const countResultItems = await this.model.findAndCountAll({
distinct: true,
subQuery: false,
col: 'Treatment.id',
include: [
{
model: DiagnosisSequelizeModel,
required: true,
where: {
patient_id: '7h95Aj1P'
}
}
]
});
console.log('Count from xxx function', countResultItems.count);
这让我回来了Count from countResultItems function 49
Raw 是正确的,因为在直接执行此操作时我得到 1 个结果sql
SELECT
`Treatment`.`id`,
`Treatment`.`diagnosis_id`,
`Treatment`.`physician_id`,
`Treatment`.`medication_id`,
`Treatment`.`country_id`,
`Treatment`.`status`,
`Treatment`.`start_date`,
`Treatment`.`end_date`,
`Treatment`.`end_reason`,
`Treatment`.`created_at`,
`Treatment`.`updated_at`,
`Treatment`.`deleted_at`,
`diagnosis`.`id` AS `diagnosis.id`,
`diagnosis`.`patient_id` AS `diagnosis.patient_id`,
`diagnosis`.`disease_id` AS `diagnosis.disease_id`,
`diagnosis`.`physician_id` AS `diagnosis.physician_id`,
`diagnosis`.`date` AS `diagnosis.date`,
`diagnosis`.`created_at` AS `diagnosis.created_at`,
`diagnosis`.`updated_at` AS `diagnosis.updated_at`,
`diagnosis`.`deleted_at` AS `diagnosis.deleted_at`
FROM
`treatment` AS `Treatment`
INNER JOIN
`diagnosis` AS `diagnosis`
ON
`Treatment`.`diagnosis_id` = `diagnosis`.`id`
AND
(`diagnosis`.`deleted_at` IS NULL AND `diagnosis`.`patient_id` = '7h95Aj1P')
WHERE
(`Treatment`.`deleted_at` IS NULL);
使用 count()
const countResultItems = await this.model.count({
distinct: true,
col: 'Treatment.id',
include: [
{
model: DiagnosisSequelizeModel,
required: true,
where: {
patient_id: '7h95Aj1P'
}
}
]
});
console.log('Count from xxx function', countResultItems);
再次返回我Count from countResultItems function 49
并且创建的缺少联接sql statement
SELECT
COUNT(DISTINCT(`Treatment`.`id`)) AS `count`
FROM
`treatment` AS `Treatment`
WHERE
(`Treatment`.`deleted_at` IS NULL);
我知道这个问题有很多问题,但基本函数甚至没有产生子句似乎很奇怪。count
join
有没有办法解决它?
续集版本 ^6.32.1
答: 暂无答案
评论