Skip to content

Instantly share code, notes, and snippets.

@jordanell
Created March 22, 2019 15:47
Show Gist options
  • Save jordanell/18c1a198a0393a6afb7c1637899a35ae to your computer and use it in GitHub Desktop.
Save jordanell/18c1a198a0393a6afb7c1637899a35ae to your computer and use it in GitHub Desktop.
Sequelize polymorphism example
this.Comment = this.sequelize.define('comment', {
title: Sequelize.STRING,
commentable: Sequelize.STRING,
commentable_id: Sequelize.INTEGER
});
this.Comment.prototype.getItem = function() {
return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)]();
};
this.Post.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'post'
}
});
this.Comment.belongsTo(this.Post, {
foreignKey: 'commentable_id',
constraints: false,
as: 'post'
});
this.Photo.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'photo'
}
});
this.Comment.belongsTo(this.Photo, {
foreignKey: 'commentable_id',
constraints: false,
as: 'photo'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment