使用Sequelize findAndCountAll关联查询报错:未知列'subCategory.name'
解决Sequelize findAndCountAll关联表字段报错问题
问题原因
findAndCountAll会执行两个独立查询:一个是带分页的列表查询,一个是总数统计查询。你用findAll正常是因为列表查询里已经包含了所有关联表,但默认情况下,count查询只会查询主表(Product),不会自动带上include里的关联表,所以当where条件用到subCategory.name时,count查询找不到这个列,直接报错。
三种解决方案
方案1:给count查询同步关联表
显式指定count查询也要包含和主查询一致的关联表,同时开启distinct避免关联表导致的重复计数:
const { count, rows } = await Product.findAndCountAll({ where: { '$subCategory.name$': { [Op.like]: '%关键词%' } }, include: [ Image, Category, { model: SubCategory, as: 'subCategory' } ], offset: page * pageSize, limit: pageSize, distinct: true, count: { include: [ Image, Category, { model: SubCategory, as: 'subCategory' } ] } });
方案2:指定按主表主键去重计数
不需要给count加关联,而是通过distinct: true和col指定按Product的主键统计,这样count查询会自动处理关联表的多行问题:
const { count, rows } = await Product.findAndCountAll({ where: { '$subCategory.name$': { [Op.like]: '%关键词%' } }, include: [ Image, Category, { model: SubCategory, as: 'subCategory' } ], offset: page * pageSize, limit: pageSize, distinct: true, col: 'Product.id' // 按Product主键去重统计总数 });
方案3:自定义count查询逻辑
如果前两种方案不适用,可以直接写原生SQL来实现count统计,完全控制查询逻辑:
const { count, rows } = await Product.findAndCountAll({ where: { '$subCategory.name$': { [Op.like]: '%关键词%' } }, include: [ Image, Category, { model: SubCategory, as: 'subCategory' } ], offset: page * pageSize, limit: pageSize, count: { query: () => sequelize.query( 'SELECT COUNT(DISTINCT `Product`.`id`) AS `count` FROM `Products` AS `Product` INNER JOIN `SubCategories` AS `subCategory` ON `Product`.`subCategoryId` = `subCategory`.`id` WHERE `subCategory`.`name` LIKE ?', { replacements: ['%关键词%'], type: sequelize.QueryTypes.SELECT } ).then(res => res[0].count) } });
补充说明
- 注意where条件里的关联表字段要写成
$subCategory.name$这种格式(Sequelize的关联字段引用语法),确保主查询能正确识别。 - 开启
distinct是因为关联表(比如Image)可能一个Product对应多个Image,会导致查询结果多行,count时会重复计数,用distinct可以保证统计的是唯一的Product数量。
内容的提问来源于stack exchange,提问作者Muhammad Amir
相关产品推荐
相关产品推荐

