Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ORM sequelize have polymorphism?

Tags:

orm

I have a model named User. Can I extend another model Admin/mod from User model? I have found the sequelize doc, but i didn't find out

like image 294
Achilles Avatar asked Aug 24 '16 04:08

Achilles


People also ask

What is polymorphic association in Sequelize?

A polymorphic association consists on two (or more) associations happening with the same foreign key. For example, consider the models Image , Video and Comment . The first two represent something that a user might post. We want to allow comments to be placed in both of them.

Are there many relations in Sequelize?

The A.hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ). These three calls will cause Sequelize to automatically add foreign keys to the appropriate models (unless they are already present).

Does Sequelize have one relationship?

Using the Sequelize hasOne() association method. The Sequelize hasOne() association method is used to establish an association between two defined Sequelize models. The association method allows you to link two models so that you can retrieve data from both tables with one query execution.


1 Answers

Yes, check out the Associations documentation, or more fully in Scopes documentation.

From the docs:

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.Image.hasMany(this.Comment, {
  foreignKey: 'commentable_id',
  constraints: false,
  scope: {
    commentable: 'image'
  }
});
this.Comment.belongsTo(this.Image, {
  foreignKey: 'commentable_id',
  constraints: false,
  as: 'image'
});
like image 197
Alex Moore-Niemi Avatar answered Nov 01 '22 17:11

Alex Moore-Niemi