我需要在我的node js代码中使用sequalize.literal。我需要做的是在序列化后的文本中使用If else语句,有没有引用呢?我尝试了下面的方法,但节点js返回该语法是错误的。有人能帮我改正语法吗?
sequelize.literal('if(userId
is not null,yes
,no
) as status
')
发布于 2021-09-03 12:37:12
我认为您真正想要的是在Sequelize子查询中使用MySQL case语句。
相关的MySQL文档是cases语句可以找到的here,子查询的序列化文档可以是here。
下面是一个与原始问题中的查询类似的示例。
let {
Sequelize,
DataTypes,
} = require('sequelize')
async function run () {
let sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {
host: 'localhost',
dialect: 'mysql',
logging: console.log
})
let Comment = sequelize.define('comment', {
userId: DataTypes.INTEGER,
comment: DataTypes.STRING
})
await sequelize.sync({ force: true })
await Comment.bulkCreate([{
comment: 'Hello'
}, {
userId: 42,
comment: 'This is it.'
}, {
userId: 128,
comment: 'Breakfast of the day.'
}])
let comments = await Comment.findAll({
attributes: [
'id',
'comment',
[ sequelize.literal('(case when userId is not null then "yes" else "no" end)'), 'status' ]
]
})
console.log(JSON.stringify(comments, null, 2))
await sequelize.close()
}
run()
下面的输出
[
{
"id": 1,
"comment": "Hello",
"status": "no"
},
{
"id": 2,
"comment": "This is it.",
"status": "yes"
},
{
"id": 3,
"comment": "Breakfast of the day.",
"status": "yes"
}
]
https://stackoverflow.com/questions/69047421
复制相似问题