【问题标题】:How to dynamically change value of query如何动态更改查询的值
【发布时间】:2018-04-13 15:18:43
【问题描述】:

我正在用 Express 构建一个应用,Postgres 作为数据库,Sequelize 作为 ORM。

我有两个模型,用户和帖子。帖子属于用户,用户可以有很多帖子。每个帖子都有一个类型,可以是 1、2 或 3。

我想访问每个用户的姓名以及他有多少帖子,按类型划分。

响应应该是这样的:

{
  "name": "John",
  "typeOne": 1,
  "typeTwo": 3,
  "typeThree": 5
}

我现在的代码是这样的:

router.route('/:id').get(async (req, res) => {
  const user = await User.findOne({
    where: { id: req.params.id },
      include: {
        model: Post,
        where: { type: 1 }
      }
    });
  const typeTwo = await User.findOne({
    where: { id: req.params.id },
      include: {
        model: Post,
        where: { type: 2 }
      }
    });
  const typeThree = await User.findOne({
    where: { id: req.params.id },
      include: {
        model: Post,
        where: { type: 3 }
      }
    });

    res.send({
      name: user.first_name,
      typeOne: user.posts.length,
      typeTwo: typeTwo.posts.length,
      typeThree: typeThree.posts.length });
  })

我得到了正确的响应,但我认为这段代码可以写得更好。编译它需要很多时间。我怎样才能得到总数?

谢谢!

【问题讨论】:

    标签: node.js postgresql express sequelize.js


    【解决方案1】:

    您可以使用groupbycount

    User.findAll({
        where: { id: req.params.id },
        attributes: {
            include: ['name', 'posts.type', [Sequelize.fn("COUNT", Sequelize.col("posts.type")), "postsCount"]] 
        },
        include: [{
            model: Post, attributes: []
        }],
        group: ['model.type'] // also try, group: ['Post.type']
    });
    

    【讨论】:

    • 好的,谢谢,我试试这个,当我需要访问帖子时会发生什么,而不仅仅是计数?
    • 是什么意思?没找到你
    • 如何访问所有帖子及其内容? Post 有一个类型和一个内容。
    • 在属性中,您可以根据需要提及所有字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2020-12-12
    • 2021-11-01
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多