node.js - TypeORM - 从 Postgres 中获取匹配(和相关)行
问题描述
我不确定标题是否清楚地定义了问题,所以我会在这里尝试解释。
我有两张桌子,一张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 的新手,所以我不确定是否有更好的方法来定义这里的关系。接受建议!
提前致谢!
解决方案
更好的方法是多制作 1 个表,例如 UserConversations 以保存 2 个表 User 和 Conversation 中的多对多。比方说:
在用户实体中:
@OneToMany()
public userConversations: UserConversation[]
在对话实体中:
@OneToMany()
public userConversations: UserConversation[]
在 UserConversation 实体中:
@ManyToOne()
public user: User
@ManyToOne()
public conversation: Conversation
推荐阅读
- c# - 是否有用于顺序应该断言的 Resharper 模式?
- htmltidy - 如何运行 HTML Tidy 以修复 HTML 中导致其格式不正确的问题,而不仅仅是报告问题?
- c# - 在 BackgroundWorker 中停止查询阅读器的好方法是什么?
- java - Tomcat 发回 HTML 而不是 servlet 过滤器的错误消息
- tsql - 使用 SUM、ORDER BY 的 SQL 查询,值有限
- linux - 如何查看电子邮件的来源?
- html - iOS - Safari - 图像未完全渲染/截断
- python - 熊猫:read_csv 错过最后几行
- python - 这是为什么 !具有特殊 sigmoid 激活函数的低精度
- d - 如何在 D 中使用 Unix Domain Socket 进行 IPC?