作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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);
});
{
"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
}
]
}
最佳答案
干得好 :
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']
})
Note :
Please read the comments in code
There might be table name issue so you need to check that , rest of the part will work 100% fine.
关于node.js - 如何在 Sequelize 中正确编写包含多个包含的复杂查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49150443/
我是一名优秀的程序员,十分优秀!