我正在使用 Express、Postgres 作为 db 和 Sequelize 作为 ORM 构建一个应用程序。
这是我得到的回应:
{
"user": {
"user_name": "John",
"post": [
{
"id": 1,
"created_at": "2018-04-16T22:52:59.054Z",
"post_titles": [
{
"title_id": 3571
},
{
"title_id": 3570
},
{
"title_id": 3569
}
]
},
],
}
}
我如何计算帖子中有多少标题?
我有4个模型:
User
, hasMany Posts
Post
,通过 Titles
有很多 PostTitles
Title
PostTitle
这是我的查询:
User.findOne({
where: { id: req.params.id },
attributes: ['id', 'user_name'],
include: [
{ model: Post,
attributes: ['id', 'created_at'],
include: {
model: PostTitles,
attributes: ['title_id']
}
}
]
})
谢谢!
最佳答案
您可以使用 count
函数。
User.findOne({
where: { id: req.params.id },
attributes: ['id', 'user_name'],
include: [
{ model: Post,
attributes: ['id', 'created_at'],
include: {
model: PostTitles,
attributes: ['title_id',[Sequelize.literal('COUNT(DISTINCT(title_id))'), 'totalcount']]
}
}
]
})
关于javascript - 如何计算模型内的嵌套元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012989/