如何计算嵌套模型的属性

时间:2018-04-24 04:18:42

标签: javascript postgresql sequelize.js

我正在使用Express,Postgres for DB和Sequelize为ORM构建应用程序。

我有4个型号:
User,其中有PostTopicsPosts User,属于Topics,有许多PostTopicTopic
User,属于PostPostTopicPostTopic 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
            }
          }
        ]
      })




我想获得每个帖子的主题数量。



COUNT




我知道postgres有一种 q = { 'aggregations':{ 'labels':{ 'nested':{ 'path':'labels' }, 'aggs':{ 'latitude':{ 'terms':{ 'field':'labels.Latitude', 'min_doc_count':3 }, 'aggs':{ 'by_top_hits':{ 'top_hits':{ 'size':3 } } } } } } } } 方法,但我无法使其发挥作用。

谢谢!

1 个答案:

答案 0 :(得分:0)

你走了,

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
      })