sequelize hasmany getter code example
Example 1: getter and setter sequelize simple way
method 1:
const Pug = db.define('pugs', {
name: {
type: Sequelize.STRING,
get () {
return this.getDataValue('name') + ' the pug'
},
set (valueToBeSet) {
this.setDataValue('name', valueToBeSet.toUpperCase())
}
}
})
const createdPug = await Pug.create({name: 'cody'})
console.log(createdPug.name)
createdPug.name = 'murphy'
console.log(createdPug.name)
Example 2: getter and setter sequelize simple way
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});
const user = await User.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName);