TypeORM关联计数查询报错:nvarchar转int类型转换失败求助
问题原因
错误提示明确是nvarchar类型的值转int失败,根源是查询中存在隐式类型不匹配:
- 数据库
community表的communityId(对应user_community的community_id)是nvarchar类型,但TypeORM在处理IN子句时,可能因实体字段定义错误,将communityId当作int类型处理,导致数据库尝试把字符串ID转成int时失败。
解决方案
1. 校验实体字段定义
确保Community实体的communityId字段类型与数据库一致,定义为字符串类型:
import { Entity, Column, PrimaryColumn } from "typeorm"; @Entity() export class Community { @PrimaryColumn({ type: "nvarchar", length: 255 }) // 匹配数据库nvarchar类型 communityId: string; // 其他字段示例 @Column({ type: "nvarchar" }) communityName: string; @Column({ type: "nvarchar" }) community_type: string; // members关联关系定义... }
2. 替换子查询为JOIN写法(推荐)
用LEFT JOIN替代IN子查询,避免隐式类型转换问题,同时解决JOIN后的数据重复问题:
communityRepository.createQueryBuilder("community") .loadRelationCountAndMap('community.member_count', 'community.members') // 关联user_community表,明确字段类型匹配 .leftJoin("user_community", "uc", "uc.community_id = community.communityId") .where("community.community_type = :type", { type: "public" }) .orWhere("uc.user_id = :userId", { userId: paginationDTO.id }) .distinct(true) // 去重,避免JOIN导致的重复数据 .orderBy("community.communityName") .skip(paginationDTO.page * paginationDTO.limit) .take(paginationDTO.limit) .getMany()
3. 若坚持使用子查询,显式保证类型匹配
如果一定要用IN子查询,确保子查询返回的community_id与community.communityId类型严格一致,可在子查询中显式指定类型(针对SQL Server):
communityRepository.createQueryBuilder("community") .loadRelationCountAndMap('community.member_count', 'community.members') .where("community.community_type = :type", { type: "public" }) .orWhere(`community.communityId IN (SELECT CAST(uc.community_id AS NVARCHAR(255)) FROM user_community uc WHERE uc.user_id = :userId)`, { userId: paginationDTO.id }) .orderBy("community.communityName") .skip(paginationDTO.page * paginationDTO.limit) .take(paginationDTO.limit) .getMany()
内容的提问来源于stack exchange,提问作者Emir Kutlugün
相关产品推荐
相关产品推荐

