Skip to content

Including related items for a polymorphic relation. #11731

Closed

Description

@onwuvic

Issue Description

What was unclear/insufficient/not covered in the documentation

Including related items for a polymorphic relation.

From the example provided in 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'
});

Getting Comment from Post and Image with post.getComments(), image.getComments() respectively works fine.

The issue now is, how to get a Comment with the related commentable items? (it can be Post or Image). For instance,

Comment.findAll({
    include: ['commentable']  // what should be here?
});

I know in the docs this was provided
Screenshot 2019-12-05 at 12 45 37

But I can't figure out how to use the getItem utility function and its usage wasn't documented on the doc. I will really be grateful if someone can explain how to use it.

If possible: Provide some suggestion on how we can enhance the docs

A real case example on how to use the getItem utility function to include all commentable will really help.

Issue Template Checklist

Is this issue dialect-specific?

  • No. This issue is relevant to Sequelize as a whole.
  • Yes. This issue only applies to the following dialect(s): XXX, YYY, ZZZ
  • I don't know.

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. added
    docs
    on Dec 5, 2019
  2. added
    status: wip
    on Dec 26, 2019
  3. self-assigned this
    on Dec 26, 2019
  4. removed
    status: wip
    on Jan 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions