Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query virtual column using Sequelize?

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
like image 730
laoqiren Avatar asked May 22 '17 00:05

laoqiren


Video Answer


1 Answers

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

like image 116
Pratyush Avatar answered Sep 30 '22 19:09

Pratyush