【发布时间】:2021-06-25 20:21:37
【问题描述】:
我不确定标题是否清楚地定义了问题,所以我会在这里尝试解释一下。
我有 2 个表,一个 Users 表和一个 Conversations 表。
Users 和 Conversations 具有 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