javascript - 如何计算模型内的嵌套元素?

标签 javascript postgresql express sequelize.js

我正在使用 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 PostsPost ,通过 Titles 有很多 PostTitlesTitlePostTitle
这是我的查询:
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/

相关文章:

javascript - Ember.js 路由器应用架构——如何拥有多个嵌套 View / Controller 对

javascript - Bootstrap 3.0 + 用于多个密码字段的 jQuery 密码强度计

javascript - 从 anchor 标记在新选项卡中打开 .docx 文件

postgresql - postgresql中 "Timestamp with zone"的默认值是什么?

java - 我可以使用 JOOQ 对查询运行 "explain analyze"吗?

node.js - 如何访问 basicAuth 内的快速路由

node.js - 如何访问声明全局的 namespace ?

javascript - mean.io assetmanager.init(... 返回 JS 错误

javascript - 在 JavaScript 中显示数百万个对象

postgresql - SQL/XML 中的 XPath1,计数元素返回空