如何在Sequlize中使用多个包含正确编写复杂查询?

时间:2018-03-07 11:09:07

标签: node.js postgresql sequelize.js

我是Sequelize ORM的新手。我有表用户,角色和投票。

我想让一个用户的角色(可能很少)和投票表的平均费率作为评级字段。我遇到了group by问题。

const id = req.params.id;
user
.findOne({
  where: { id },
  attributes: [
    "id",
    "username",
    "email",
    "avatar",
    "createdAt",
  ],
  include: [
    { model: role, attributes: ["name"] },
    { model: vote, attributes: ["rate"] },
  ],
})
.then(user => {
  res.status(200).json({ user });
})
.catch(err => {
  console.log(err);
});

上面的代码获得下一个json

{
  "id": 2,
  "username": "John Connor",
  "email": "johny@gmail.com",
  "avatar": "/public/static/img/uploads/avatar.jpg",
  "createdAt": "2018-03-05T20:25:56.693Z",
  "role": {
    "name": "USER_ROLE"
  },
  "votes": [
    {
      "rate": 4
    },
    {
      "rate": 5
    },
    {
      "rate": 2
    }
  ]
}

我不知道如何正确地执行复杂查询并获得平均值 而不是让所有领域率。你怎么做这样的查询? 也许我应该单独做这个或者有点不同?

2 个答案:

答案 0 :(得分:1)

你走了:

user.findOne({
    where: { id },
    attributes: [
        "id",
        "username",
        "email",
        "avatar",
        "createdAt",
        [sequelize.fn('AVG', sequelize.col('votes.rate')) ,'average_vote'] // perform average function like this
    ],
    include: [
        { model: role, attributes: ["id","name"] },
        { model: vote, attributes: [] }, // remove all the attributes from vote model
    ],
    // group by by the rest 2 table's (change user. and role. as per table name or query)
    group : ['user.id','role.id']

})
  

注意:

     
      
  1. 请阅读代码

  2. 中的评论   
  3. 可能存在表格名称问题,因此您需要检查一下,其余部分将100%正常工作。

  4.   

答案 1 :(得分:0)

试试这个:

const id = req.params.id;
user
.findOne({
  where: { id },
  attributes: [
    "id",
    "username",
    "email",
    "avatar",
    "createdAt",
  ],
  include: [
    { model: role, attributes: ["name"] },
    { model: vote, attributes: [[sequelize.fn('avg', sequelize.col('rate')), 'rate']] },
  ],
group: ['id', 'username', 'email', 'avatar', 'createdAt', 'name'],
})
.then(user => {
  res.status(200).json({ user });
})
.catch(err => {
  console.log(err);
});