objection.js modifyEager .as('count') 似乎对 .count() 没有任何作用
objection.js modifyEager .as('count') doesn't seem to do anything to .count()
所以我想获取 post 中的评论数,而不是所有评论本身
我已经让它像这样与 modifyEager 一起工作,但 as('count')
在这种情况下似乎什么也没做
.eager('comments').modifyEager("comments", builder => {
builder.count().as('count')
})
这真的很乏味,因为每个 post 的 commentsCount 具有这些值:
[]
[]
[]
[]
[ Post { 'count(*)': 1 } ]
[]
所以我已经知道这样做了,但我肯定做错了什么
if(commentCount.length > 0)
return data[0]["count(*)"]
return 0
有什么想法吗?
编辑:显示工作代码以供参考以帮助人们
module.exports = async (organizationId, scope) => {
return await Post.query()
.where("organization_id", organizationId)
.orderBy("post_id", "desc")
.limit(scope.limit)
.offset(scope.offset)
.select(
'posts.*',
Post.relatedQuery('comments').count().as('commentsCount')
)
.eager('users')
}
无法测试,但示例以这种方式出现在文档中:
const posts = await Post
.query()
.select(
'Post.*',
Post.relatedQuery('comments').count().as('numberOfComments')
);
console.log(posts[4].numberOfComments);
所以我想获取 post 中的评论数,而不是所有评论本身
我已经让它像这样与 modifyEager 一起工作,但 as('count')
在这种情况下似乎什么也没做
.eager('comments').modifyEager("comments", builder => {
builder.count().as('count')
})
这真的很乏味,因为每个 post 的 commentsCount 具有这些值:
[]
[]
[]
[]
[ Post { 'count(*)': 1 } ]
[]
所以我已经知道这样做了,但我肯定做错了什么
if(commentCount.length > 0)
return data[0]["count(*)"]
return 0
有什么想法吗?
编辑:显示工作代码以供参考以帮助人们
module.exports = async (organizationId, scope) => {
return await Post.query()
.where("organization_id", organizationId)
.orderBy("post_id", "desc")
.limit(scope.limit)
.offset(scope.offset)
.select(
'posts.*',
Post.relatedQuery('comments').count().as('commentsCount')
)
.eager('users')
}
无法测试,但示例以这种方式出现在文档中:
const posts = await Post
.query()
.select(
'Post.*',
Post.relatedQuery('comments').count().as('numberOfComments')
);
console.log(posts[4].numberOfComments);