【问题标题】:How to count nested elements inside a model?如何计算模型中的嵌套元素?
【发布时间】:2018-04-25 02:00:09
【问题描述】:

我正在使用 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,有很多 TitlesPostTitles
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']
      }
    }
  ]
})

谢谢!

【问题讨论】:

    标签: javascript postgresql express sequelize.js


    【解决方案1】:

    你可以使用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']]
          }
        }
      ]
    })
    

    【讨论】:

    • 我收到此错误Unhandled rejection SequelizeDatabaseError: column "users.id" must appear in the GROUP BY clause or be used in an aggregate function。我添加了group: 'users.id',但我得到`对表“post_titles”的 FROM 子句条目的无效引用
    • 也通过 users.id 传递组。并再次检查group : ['users.id']
    猜你喜欢
    • 2013-09-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多