![](/img/trans.png)
[英]Sequelize: use field created in sequelize.literal in where clause
[英]Why I got “sequelize.literal is not a function” in Sequelize
我尝试将我的项目克隆到新 PC,然后我收到一个错误调用“sequelize.literal 不是函数”。
这是我的产品 controller。 我尝试通过使用文字 function 来获得具有 avg_rating 的产品。
const Product = require("../models").product;
module.exports = {
getProduct: async (req, res) => {
try {
let query = {}
query.where = {
isPublished: 1
};
query.attributes = {
include: [
sequelize.literal(
`(SELECT CAST(AVG(rating) AS DECIMAL(10,1)) FROM product_reviews WHERE productId = \`Product\`.\`id\`)`
),
"avg_rating",
]
}
const product = await Product.findAll(query)
res.send({
status: 200,
data: product,
});
} catch (error) {
res.status(500).send({
error: error.message,
});
}
},
}
对于结果
状态 500 和错误:“sequelize.literal 不是函数”
我的 package.json 在这里。
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"dev": "nodemon app.js"
},
"author": "NuChaiyakorn",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cookie-session": "^1.4.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-fileupload": "^1.1.7-alpha.3",
"express-promise-router": "^3.0.3",
"faker": "^4.1.0",
"ffmpeg": "0.0.4",
"joi": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"morgan": "^1.10.0",
"mysql2": "^2.1.0",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"ramda": "^0.27.0",
"randomstring": "^1.1.5",
"sequelize": "^5.21.6",
"slugify": "^1.4.0"
}
}
最后我通过将此行添加到 controller 的顶部来解决问题。
const { sequelize } = require('../models/index')
您的attributes
应如下所示 -
query.attributes = [
[sequelize.literal(`(SELECT CAST(AVG(rating) AS DECIMAL(10,1)) FROM product_reviews WHERE productId = \`Product\`.\`id\`)`), 'avg_rating']
];
您还需要指定响应中所需的额外属性以及avg_rating
。
例如 -
query.attributes = [
'id',
['name','userName'],
[sequelize.literal(`(SELECT CAST(AVG(rating) AS DECIMAL(10,1)) FROM product_reviews WHERE productId = \`Product\`.\`id\`)`), 'avg_rating']
];
我尝试像您使用的那样将attributes
与include
一起使用,但没有得到预期的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.