我认为您真正想要的是在 sequelize 子查询中使用 MySQL case 语句。
相关 MySQL 文档 for case 语句可以找到here,子查询的 sequelize 文档可以是 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"
}
]