首页 > 解决方案 > TypeORM - 从 Postgres 中获取匹配(和相关)行

问题描述

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

我有两张桌子,一张Users桌子和一张Conversations桌子。

Users并且ConversationsMany-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.jstypescriptpostgresqltypeormnode.js-typeorm

解决方案


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

在用户实体中:

@OneToMany()
public userConversations: UserConversation[]

在对话实体中:

@OneToMany()
public userConversations: UserConversation[]

在 UserConversation 实体中:

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

推荐阅读