我有以下 sequelize 测试用例,我试图在其中返回模型上关系的计数。
test('Tag with file count', async () => {
const tagOne = await db.Tag.create({
label: 'One'
})
const tagTwo = await db.Tag.create({
label: 'Two'
})
const tagThree = await db.Tag.create({
label: 'Three'
})
const tagFour = await db.Tag.create({
label: 'Four'
})
const tagFive = await db.Tag.create({
label: 'Five'
})
const fileOne = await db.File.create()
const fileTwo = await db.File.create()
await fileOne.setTags([tagOne, tagTwo, tagFour])
await fileTwo.setTags([tagOne, tagTwo, tagThree])
const output = await db.Tag.findAll({
attributes: {
include: [
[Sequelize.fn('COUNT', 'Files.id'), 'fileCount']
]
},
include: [
{
model: db.File,
as: 'files',
attributes: [],
duplicate: false
}
],
group: 'Tag.id',
order: [
[Sequelize.literal('`fileCount`'), 'DESC']
]
})
expect(output.length).toBe(5)
expect(output.find(tag => tag.label === tagOne.label).dataValues.fileCount).toBe(2)
expect(output.find(tag => tag.label === tagTwo.label).dataValues.fileCount).toBe(2)
expect(output.find(tag => tag.label === tagThree.label).dataValues.fileCount).toBe(1)
expect(output.find(tag => tag.label === tagFour.label).dataValues.fileCount).toBe(1)
expect(output.find(tag => tag.label === tagFive.label).dataValues.fileCount).toBe(0)
})
对于 tagFive,我希望列 fileCount 为 0,但它返回 1。对于其他人,它似乎返回正确的文件计数。
findAll 中是否缺少选项或错误?
编辑
我生成了以下查询
Executing (default): SELECT `Tag`.`id`,
`Tag`.`label`,
`Tag`.`slug`,
`Tag`.`createdAt`,
`Tag`.`updatedAt`, COUNT('Files.id') AS `fileCount`,
`files->FileTags`.`createdAt` AS `files.FileTags.createdAt`,
`files->FileTags`.`updatedAt` AS `files.FileTags.updatedAt`,
`files->FileTags`.`FileId` AS `files.FileTags.FileId`,
`files->FileTags`.`TagId` AS `files.FileTags.TagId`
FROM `Tags` AS `Tag`
LEFT OUTER JOIN `FileTags` AS `files->FileTags`
ON `Tag`.`id` = `files->FileTags`.`TagId`
LEFT OUTER JOIN `Files` AS `files`
ON `files`.`id` = `files->FileTags`.`FileId`
GROUP BY `Tag`.`id` ORDER BY `fileCount` DESC;
尽管有很多别名,但我对加入感到不舒服。
最佳答案
我对可以在我的数据库中使用类似结构的内容进行了一些更改...这确实返回了一些 0 计数行,但是这是我正在运行的 postgres,您显然使用了不同的东西
SELECT tag.id,
COUNT(story.id) AS fileCount
FROM tag
LEFT OUTER JOIN story_tag
ON tag.name = story_tag.tag
LEFT OUTER JOIN story
ON story.id = story_tag.story_id
GROUP BY tag.id ORDER BY fileCount DESC;
关于javascript - sequelize 中的计数关系返回 1 而不是 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60475215/