typeorm关联查询某个数据项的total应该怎么写?-灵析社区

导师小jio

const user = this.userRepository .createQueryBuilder('user') .leftJoin('user.tel', 'tel') .addSelect('COUNT(DISTINCT tel.id)', 'totalTel') .groupBy('user.id') .getOne(); return user; 一个user有多个tel,是一对多的关系,现在我需要查询某个user,并且关联出tel的数量,上面的写法,user没有totalTel字段。 { id:1, userName: 'aaa' } 而改成getRawOne就有totalTel字段,但是其他字段都是数据库定义的下划线,而非驼峰的形式。 { id:1, user_name: 'aaa', totalTel: 1, } getOne应该怎么增加totalTel字段。

阅读量:22

点赞量:0

问AI
async findOneWithTelCount(userId: number): Promise { const rawData = await this.userRepository .createQueryBuilder('user') .leftJoin('user.tel', 'tel') .select([ 'user.id AS id', 'user.userName AS userName', 'COUNT(DISTINCT tel.id) AS totalTel' ]) .where('user.id = :userId', { userId }) // 如果你有过滤条件,比如获取特定的 user .groupBy('user.id') .getRawOne(); if (!rawData) return null; return { id: rawData.id, userName: rawData.userName, totalTel: +rawData.totalTel }; }