How to query virtual column using Sequelize?

10,171

You might want to check the Sequelize.VIRTUAL datatype.

So something like this might be needed in Student model definition:

Student = sequelize.define('student', {
    ...
    birthYear: {
        type: Sequelize.VIRTUAL(Sequelize.INTEGER, "(2017 - `students`.age) as birthYear")
    }
}

More examples are available here: https://github.com/sequelize/sequelize/issues/7350

Share:
10,171
laoqiren
Author by

laoqiren

I'm a web developer now working in Bytedance Inc. --- July, 2019

Updated on June 23, 2022

Comments

  • laoqiren
    laoqiren almost 2 years

    There is a Sage in Student table, I want to query the year of birth of a student using 2017-Sage, but I don't know how to do it, I have tried to do like this:

    db.Student.findAll({
            attributes: ['Sname','Ssex',[2017-Sequelize.col('Sage'),'Year of birth']],
            where: {
                Clno: {
                    $in: ['01311','10665']
                }
            }
        })
    

    but it comes the error:

    UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: attr[0].indexOf is not a function
    
  • Pelle Jacobs
    Pelle Jacobs almost 4 years
    It seems like using ticks does no longer work. Instead, you can pass a tuple with a literal and the alias through as one of the attributes the virtual column depends on: Sequelize.VIRTUAL(Sequelize.INTEGER, [[Sequelize.literal("2017 - students.age"), "birthYear"]])