Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pranildasika
Created June 21, 2012 06:26
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save pranildasika/2964211 to your computer and use it in GitHub Desktop.
Save pranildasika/2964211 to your computer and use it in GitHub Desktop.
Virtual fields using getter and setter methods in sequelize
var Sequelize = require('sequelize')
var sequelize = new Sequelize('sequelize_test', 'root')
//Note that the model definition does not have "fullName"
var User = sequelize.define('User', {
email: Sequelize.STRING,
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
},
{
getterMethods: {
fullName: function() {
return this.firstName + '' + this.lastName
}
},
setterMethods: {
fullName: function(fullname) {
var split = fullname.split(''),
this.firstName = split[0],
this.lastName = split[1]
}
}
})
sequelize.sync().success(function() {
User
.create({ email: 'john@smith.com', fullName: 'John Smith' })
.success(function(jsmith){ console.log(jsmith.fullName) })
})
@danhstevens
Copy link

Huge help. Thanks!

@travisby
Copy link

Thanks!

@kashishgupta1990
Copy link

Thanks very help full

@juliocanares
Copy link

Thanks :D , but this cannot order , when Model.findAll({order: 'virtualField' DESC'}) ?

@daniellizik
Copy link

Took me too long to figure out why my getter wasn't working on a find query.

var attrs = {
    firstname: Sequelize.STRING,
    lastname: Sequelize.STRING
};

var methods = {
    getterMethods: {
        fullname: function() { return this.firstname + " " + this.lastname; }
    }
};

var Person = sequelize.define("Person", attrs, methods);

And then later....

models.Person.find({
    attributes: ["firstname"],
    where: {id: id}
}).then(function(row) {
    console.log(row.fullname); //returns undefined because you have to specify ["firstname", "lastname"] in your query
});

I was misunderstanding in what context this[attribute] was operating in your getter/setter methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment