首页 > 解决方案 > 如何在节点 js 中使用 sequalize.literal IF 语句

问题描述

我需要在我的节点 js 代码中使用 sequalize.literal。我需要做的是在该 sequalize 文字中使用 If else 语句,是否有任何参考?我尝试了以下方式,但返回该语法的节点 js 是错误的。有人可以帮我纠正语法吗?

sequelize.literal('if( userIdis not null, yes, no) as status')

标签: javascriptmysqlsequelize.js

解决方案


我认为您真正想要的是在 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"
  }
]

推荐阅读