如何通过联结/联接表定义特殊的一对多关系

时间:2020-03-26 12:11:24

标签: typescript typeorm

我正在为三个表建模:

Comments (id, body)
Attachments (id, url)
CommentAttachments (commentId, attachmentId)

一个评论可以有很多附件,但是一个附件只能属于一个评论,或者根本没有评论。

检索注释时,我也想自动填充所有关联的附件,这就是我在努力正确定义的问题。

这是我到目前为止所拥有的:

Comment.ts

@Entity({ name: "comments" })
export class Comment {
  @PrimaryGeneratedColumn("uuid")
  id!: string;

  @Column({ name: "body", type: String, nullable: true })
  body!: string | null;

  // ???
  // attachments: Attachment[];
}

Attachment.ts

@Entity({ name: "attachments" })
export class Attachment {
  @PrimaryGeneratedColumn("uuid")
  id!: string;

  @Column({ name: "url", type: String })
  url!: string;
}

CommentAttachment.ts

@Entity({ name: "comment_attachments" })
export class CommentAttachment {
  @PrimaryColumn({ name: "comment_id", type: "uuid" })
  commentId!: string;

  @OneToOne(() => Comment)
  @JoinColumn({ name: "comment_id" })
  comment!: Comment;

  @PrimaryColumn({ name: "attachment_id", type: "uuid" })
  attachmentId!: string;

  @OneToOne(() => Attachment)
  @JoinColumn({ name: "attachment_id" })
  attachment!: Attachment;
}

我想要的是这样的:

const comments = await this.commentRepository.find({ relations: ["attachments"] });
console.log(comments);
/*
  [
    {
      id: "id1",
      body: "some comment",
      attachments: [
        {
          id: "attid1",
          url: "some url"
        }
      ]
    }
  ]
*/

这可能仅与正确定义的实体有关吗?

如果可能的话,我想保留联接表,而不在附件表中引入可选的commentId列。

0 个答案:

没有答案