【问题标题】:TypeORM - Get Matching (and related) rows form PostgresTypeORM - 从 Postgres 中获取匹配(和相关)行
【发布时间】:2021-06-25 20:21:37
【问题描述】:

我不确定标题是否清楚地定义了问题,所以我会在这里尝试解释一下。

我有 2 个表,一个 Users 表和一个 Conversations 表。

UsersConversations 具有 Many-to-Many 关系。

用户实体:

排除其他列

@ManyToMany(() => Conversation, (conversationEntity) => conversationEntity.participants)
    conversations: Conversation[];

对话实体:

排除其他列

@ManyToMany(() => User, userEntity => userEntity.conversations)
    @JoinTable()
    participants: User[];

连接表中的数据如下所示:

现在,我想获取特定用户的所有对话。但我也想获得相关的行。例如在上图中,我想获取这两行,因为这两行属于同一个对话。但是由于我是根据 userId 进行搜索的,所以查询会跳过与 userId 不匹配的行。

这是我正在使用的 TypeORM 查询:

const [results, totalCount] = await this.conversationsRepo
  .createQueryBuilder('conversations')
  .leftJoin('conversations.participants', "participants")
  .andWhere('participants.id = :userId', {userId})
  .addSelect(['participants.fullName', 'participants.id'])
  .getManyAndCount();

有什么方法可以让其他参与者也参与进来吗?我是 TypeORM 和 Postgres 的新手,所以我不确定是否有更好的方法来定义这里的关系。接受建议!

提前致谢!

【问题讨论】:

    标签: node.js typescript postgresql typeorm node.js-typeorm


    【解决方案1】:

    更好的方法是多制作 1 个表,例如 UserConversations 来保存 2 个表 User 和 Conversation 中的多对多。比方说:

    在用户实体中:

    @OneToMany()
    public userConversations: UserConversation[]
    

    在对话实体中:

    @OneToMany()
    public userConversations: UserConversation[]
    

    在 UserConversation 实体中:

    @ManyToOne()
    public user: User
    @ManyToOne()
    public conversation: Conversation
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2020-04-24
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      相关资源
      最近更新 更多