Ali Sherafat
Ali Sherafat

Reputation: 3855

Sequelize include related item for polymorphic relation

From the docs we have a Comment model with a polymorphic relation to Image and Post:

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'
});

Now, how to get a Comment with related commentable item? (it can be Post or Image)

Comment.findOne({
    where: {title: 'sequelize'},
    include: ['commentable']  // what should be here?
});

Upvotes: 1

Views: 1364

Answers (1)

Tai Luis
Tai Luis

Reputation: 11

From the doc

The getItem utility function on Comment completes the picture - it simply converts the commentable string into a call to either getImage or getPost, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to getItem(options) to specify any where conditions or includes.

Reference topic Sequelize ORM: polymorphic associations 1:m possible?. I hope this help you out.

Upvotes: 1

Related Questions