join Subquery with typeorm"/>
Left join Subquery with typeorm
我有下表
文章、用户和评论。一个用户可以有多个评论和文章,我正在尝试编写一个查询,选择
Comments
列表以及 User
信息和由 Article
编写的总 User
。下面的查询
thismentRepository
.createQueryBuilder('comment')
.leftJoinAndSelect('commentmentRatings', 'commentRatings')
.leftJoinAndSelect('comment.user', 'user')
.where('comment.articleId = :id', { id })
.select([
'comment.id',
'commentment',
'user.name',
'user.profilePhoto',
'user.createdOn',
'commentRatings',
'comment.createdOn',
])
.orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
.offset(offset)
.limit(limit)
.getMany()
返回我需要的
User
信息,Comment
和Rating
,每个用户的articlesCount
是我无法得到的。我尝试添加一个subQuery
作为leftJoinAndSelect
喜欢
const userPostsQuery = thismentRepository
.createQueryBuilder()
.subQuery()
.from(User, 'user')
.leftJoinAndSelect('user.posts', 'article')
.select('SUM(user.id)', 'sum')
.getQuery();
和
thismentRepository
.createQueryBuilder('comment')
.leftJoinAndSelect('commentmentRatings', 'commentRatings')
.leftJoinAndSelect('comment.user', 'user')
.loadRelationCountAndMap('comment.article', 'article')
.leftJoinAndSelect(userPostsQuery, 'userPostsQuery')
.where('comment.articleId = :id', { id })
.select([
'comment.id',
'commentment',
'user.name',
'user.profilePhoto',
'user.createdOn',
'commentRatings',
'comment.createdOn',
])
.orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
.offset(offset)
.limit(limit)
.getMany()
上面的查询抛出一个错误 > error: syntax error at or near
"WHERE"
然后我试了
thismentRepository
.createQueryBuilder('comment')
.leftJoinAndSelect('commentmentRatings', 'commentRatings')
.leftJoinAndSelect('comment.user', 'user')
.leftJoinAndSelect(
(qb) =>
qb
.from(Article, 'article')
.leftJoinAndSelect('article.user', 'user')
.loadRelationCountAndMap('article.user', 'article.user'),
'userQuery',
)
.where('comment.articleId = :id', { id })
.select([
'comment.id',
'commentment',
'user.name',
'user.profilePhoto',
'user.createdOn',
'commentRatings',
'comment.createdOn',
])
.orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
.offset(offset)
.limit(limit)
.getMany()
抛出错误
error:
处或附近的语法错误"WHERE"
请问如何在每个
totalArticle
行中按用户附加Comment
?任何帮助将不胜感激。
回答如下:
您可以使用
loadRelationCountAndMap
方法加载每个用户的文章总数。
更多示例用法.
示例代码:
thismentRepository
.createQueryBuilder('comment')
.leftJoinAndSelect('commentmentRatings', 'commentRatings')
.leftJoinAndSelect('comment.user', 'user')
.leftJoinAndSelect('user.articles', 'article')
.loadRelationCountAndMap('user.totalArticle', 'user.articles')
.where('comment.articleId = :id', { id })
.select([
'comment.id',
'commentment',
'user.name',
'user.profilePhoto',
'user.createdOn',
'commentRatings',
'comment.createdOn',
])
.orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
.offset(offset)
.limit(limit)
.getMany()
更多推荐
Left join Subquery with typeorm
发布评论