[英]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.