javascript - 如何计算嵌套模型的属性

标签 javascript postgresql sequelize.js

我正在使用 Express、用于 DB 的 Postgres 和用于 ORM 的 Sequelize 构建应用程序。

我有4个模型:User ,他有很多 Post 和很多 TopicsPosts ,属于User,通过Topics有很多PostTopicTopic ,通过 User 属于 PostPostTopicPostTopic 属于 PostTopic
这是我得到的回应:

"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/

相关文章:

javascript - 为什么广告在我的开发盒上停止呈现?

javascript - JQuery 加载效果/动画

javascript - 如何使用 javascript 创建 Soundcloud 播放列表(设置)?

postgresql - 为什么 psycopg2 对重复的 SELECT 返回相同的结果?

postgresql - Laravel postgresql 不区分大小写

Sql 选择具有 column1 值的行出现多个 column2 值

postgresql - 在生成 SQL 以获取 n :m associated models? 时,如何让 sequelize 不使用时间戳字段

javascript - AngularJS + ag-grid : sticky/remembered selections with virtual paging/infinite scrolling

javascript - Postgres 的 Sequelize-auto

node.js - 在 Sequelize 中获取刚刚保存的对象的 id?