NestJS中使用TypeORM查询关联会诊数据时返回空数组问题
问题排查与解决方案
核心问题:查询条件写法错误
当前查询会诊时使用整个user实体作为doctor的匹配条件,TypeORM无法正确解析这种写法,导致生成的SQL条件不符合预期,返回空数组。
修正后的查询代码
将查询条件改为明确匹配医生ID:
const consultation = await this.consultationRepo.find({ where: { doctor: { id: user.id }, // 直接指定关联实体的主键字段 }, relations: ['patient', 'patient.history', 'patient.prescriptions'], });
如果你的ConsultationEntity中显式定义了外键字段(比如doctorId),也可以直接用外键查询,更高效:
// 假设ConsultationEntity中有@Column() doctorId: number; const consultation = await this.consultationRepo.find({ where: { doctorId: user.id }, relations: ['patient', 'patient.history', 'patient.prescriptions'], });
额外排查点
确认反向关联定义
检查DoctorEntity中是否正确定义了与ConsultationEntity的OneToMany关联:@OneToMany(() => ConsultationEntity, consultation => consultation.doctor) consultation: ConsultationEntity[];(注:此关联不影响当前从
consultationRepo的查询,但确保关联关系双向完整性)验证数据库数据
直接执行SQL查询验证数据库中是否存在匹配记录:SELECT * FROM consultation WHERE doctor_id = [你的医生ID];如果查询不到结果,说明数据存储时可能存在关联错误,需要检查保存会诊数据的代码是否正确关联了医生实体。
使用QueryBuilder排查
若问题仍存在,改用QueryBuilder查询,可直观查看生成的SQL:const consultation = await this.consultationRepo .createQueryBuilder('consultation') .leftJoinAndSelect('consultation.patient', 'patient') .leftJoinAndSelect('patient.history', 'history') .leftJoinAndSelect('patient.prescriptions', 'prescriptions') .where('consultation.doctor.id = :doctorId', { doctorId: user.id }) .getMany();查看控制台输出的SQL语句,确认条件是否正确。
内容的提问来源于stack exchange,提问作者Noel
相关产品推荐
相关产品推荐

