Skip to content

Polymorphic Relationships #45

Closed
Closed
@chrissm79

Description

@chrissm79

First off, thank you for this package, it's made my transition to Sequelize insanely easy!

I'm running into an issue w/ polymorphic relationships. On the sequelize docs, it mentions that I need to set a scope and a constraints on the HasMany side of the relationship and a constraints and as on the BelongsTo side). There's also unique, scope, and constraints options on the BelongsToMany relationships.

Would something like a function overload be possible here to allow us to pass in the additional options w/ an object?

// 1:m
class Post extends Model<Post> {
  // ...
  @HasMany({ 
    model: () => Comment,
    constraints: false, 
    scope: { commentable: "post" }
  }, 'foreign_key')
  comments: Comment[];
}

class Comment extends Model<Comment> {
  // ...
  @BelongsTo({ 
    model: () => Post,
    constraints: false, 
    as: "post" }, 
    'foreign_key'
  )
  post: Post;
}
// n:m
class Post extends Model<Post> {
  // ...
  @BelongsToMany(
    () => Tag,
    { 
      through: () => ItemTag,
      unique: false, 
      constraints: false,
      scope: { taggable: "post" }
    }, 
    'foreign_key'
  )
  tags: Tag[];
}

class Tag extends Model<Tag> {
  // ...
  @BelongsToMany(
    model: () => Post,
    { 
      through: () => ItemTag
      unique: false, 
    },
    {
      foreignKey: 'foreign_key',
      constraints: false
    }
  )
  post: Post;
}

class ItemTag extends Model<ItemTag> {
  // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions