【问题标题】:Is there a way to get all Entity records through a custom pivot table有没有办法通过自定义数据透视表获取所有实体记录
【发布时间】:2022-12-29 12:58:54
【问题描述】:

我正在尝试在我的项目中创建推文书签功能。用户可以在其中保存推文以供以后查看。在给定 userId 和 tweetId 的情况下,我能够访问端点并保存书签表记录。我无法弄清楚如何使用 typeorm 返回所有已添加书签的推文。一个用户可以有多个书签。

我在 mysql 数据库中有以下三个实体

推文.entity.ts

@Entity()
export class Tweet {
    @PrimaryGeneratedColumn()
    public id?: number;

    @Column('text')
    public text: string;

    @ManyToOne(() => User, (user: User) => user.tweets)
    public user: User;

    @OneToMany(() => Comment, (comment: Comment) => comment.tweet)
    public comments: Comment[];
}

用户.entity.ts

@Entity()
class User {
  @PrimaryGeneratedColumn()
  public id?: number;
 
  @Column({ unique: true })
  public email: string;

  @OneToMany(() => Tweet, (tweet: Tweet) => tweet.user)
  public tweets: Tweet[];
}

书签.entity.ts

@Entity()
export class Bookmark {
    @PrimaryGeneratedColumn()
    public id?: number;
    
    @Column()
    public userId: number;
    
    @Column()
    public tweetId: number;    
}

【问题讨论】:

    标签: node.js nestjs typeorm


    【解决方案1】:

    使用查询生成器的一种解决方案:

    const items = await dataSource
        .createQueryBuilder(tweet, "tweet")
        .innerJoin("bookmark", "bookmark", "bookmark.tweetId = tweet.id")
        .where("bookmark.userId = :userId", { userId: userId })
        .getMany();
    

    您还可以使用 Bookmark 作为数据透视表声明 Tweet 和 User 之间的多对多关系:

    用户.entity.ts

    @ManyToMany(type => Tweet)
    @JoinTable({
        name: "bookmarks", // pivot table name
        // Custom column name
        // joinColumn: {
        //    name: "userId",
        //    referencedColumnName: "id"
        // },
        // inverseJoinColumn: {
        //    name: "tweetId",
        //    referencedColumnName: "id"
        // }
    })
    bookmarks: Tweet[];
    

    用法:

    userRepository.find({
      relations: ["bookmarks"],
    })
    

    更多信息:https://github.com/typeorm/typeorm/blob/master/docs/relations.md#jointable-options

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2020-04-28
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多