【问题标题】:How to use sequalize.literal IF statement in node js如何在节点js中使用sequelize.literal IF语句
【发布时间】:2021-11-01 22:37:35
【问题描述】:

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

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

【问题讨论】:

    标签: javascript mysql sequelize.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 2015-01-26
      相关资源
      最近更新 更多