javascript - 如何在节点 js 中使用 sequalize.literal IF 语句
问题描述
我需要在我的节点 js 代码中使用 sequalize.literal。我需要做的是在该 sequalize 文字中使用 If else 语句,是否有任何参考?我尝试了以下方式,但返回该语法的节点 js 是错误的。有人可以帮我纠正语法吗?
sequelize.literal('if( userId
is not null, yes
, no
) as status
')
解决方案
我认为您真正想要的是在 sequelize 子查询中使用 MySQL case 语句。
相关的 MySQL 文档用于 case 语句可以在这里找到,而用于子查询的 sequelize 文档可以在这里。
这是一个类似于原始问题中的查询的示例。
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"
}
]
推荐阅读
- mysql - Mysql 1406 列的数据太长
- sql - ORA-00904:“好”:无效标识符 ORA-06512
- macos - productsign 仍然要求输入密码,即使钥匙串已解锁并且证书已获得导入许可
- c - 程序在 for 循环处停止
- asp.net-mvc - aspNet Core - 身份 - applicationUser,不是自动生成的吗?
- reactjs - 我在创建 apk 文件博览会时遇到这种类型的错误
- flutter - Flutter Empty 构造值
- python - 无法从 python 执行两个 SQL 表的内连接,出现通信链接错误/连接写入错误
- python-3.x - valueError:时间数据“2021-02-01T04:10:39.669Z”与格式“%Y-%m-%dT%M:%H:%S%f%z”不匹配
- firebase - 使用颤振将不超过 2 个图像存储在 Firebase 中