Skip to content

id relation in attribute #1

@mdarveau

Description

@mdarveau

Hi Ahmer!
Thank for the excellent article https://vivacitylabs.com/setup-typescript-sequelize/. It was super useful in my TS migration.

I have a comment on the article and this is the only way I found to reach you. :-)

In CommentAttributes, you add the relation attribute as post?: PostAttributes | PostAttributes['id'];.

I don't think the PostAttributes['id'] part is right as Sequelize accept the numeric id of the relation only when passed in a postID attribute on create.

Comment.create(
  text: "some text",
  postId: 123
)

works, but

Comment.create(
  text: "some text",
  post: 123
)

doesn't.

The listing would then be:

export interface CommentAttributes {
  id?: number;
  text: string;
  createdAt?: Date;
  updatedAt?: Date;

  // ** this is new **

  // We allow both either PostAttributes or a Post's primary key,
  // so we can specifiy either when we create a model.
  // `posts?` is optional because we don't want to force
  // specifying associations when we create a model. We also
  // want to be able to query for Comment's without also having
  // to load its posts.
  post?: PostAttributes;
  postId?: PostAttributes['id'];

  // Similarly, we define the field `author?`. An `author` is an
  // alias for the `User` model, so we define that `author?` can
  // either be a `UserAttributes` or a `UserAttributes['id']`.
  author?: UserAttributes;
  authorId?: UserAttributes['id'];

  // `upvoters` is a BelongsToMany association, so we define that
  // a comment can have an array of User's, under the field `upvoters`.
  upvoters?: UserAttributes[];
  upvotersIds?: UserAttributes['id'][];
};

I'm not sure about the upvotersIds TBH :-D.

Cheers,

Manuel

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions