我正在使用 Express、用于 DB 的 Postgres 和用于 ORM 的 Sequelize 构建应用程序。
我有4个模型:User
,他有很多 Post
和很多 Topics
Posts
,属于User
,通过Topics
有很多PostTopic
Topic
,通过 User
属于 Post
和 PostTopic
PostTopic
属于 Post
和 Topic
这是我得到的回应:
"users": [
{
"id": 1,
"created_at": "2018-04-16T22:52:59.054Z",
"post": [
{
"id": 1,
"post_topic": [
{topic_id: 1},
{topic_id: 2}
]
},
{
"id": 2
"post_topic": [
{topic_id: 3},
{topic_id: 4},
{topic_id: 5}
]
},
]
},
]
我想获得每篇文章的主题数。
User.findOne({
where: { id: req.params.id },
include: [
{ model: Post,
include: {
model: PostTopic
}
}
]
})
我知道 postgres 有一个
COUNT
方法,但我无法让它工作。谢谢!
最佳答案
干得好 ,
User.findAll({
where: { id: req.params.id },
attributes : [ 'user.*' , sequelize.fn('count', db.sequelize.fn('DISTINCT', db.sequelize.col('user_posts.id'))) ]
include: [
{
model: UserPost,
attributes : [] // <------- Note this --------
}
],
group :[''user.id','user_posts.id'] // <--- Change name as per your table name
})
关于javascript - 如何计算嵌套模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993358/