You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM如何通过多对多关联查询同时包含两个指定用户的会话

方案1:双内连接实现(符合你的猜想思路)

你可以为两个要匹配的用户分别设置不同的关联别名做两次内连接,只有同时关联到两个用户的会话才会被保留:

const targetConversation = await conversationRepository
  .createQueryBuilder("c")
  // 关联第一个用户
  .innerJoin("c.attendees", "u1", "u1.id = :userId1", { userId1: 你的第一个用户ID })
  // 关联第二个用户,用不同的别名避免冲突
  .innerJoin("c.attendees", "u2", "u2.id = :userId2", { userId2: 你的第二个用户ID })
  // 如果需要返回会话的所有参会者信息,加下面这行,不需要可以去掉
  .leftJoinAndSelect("c.attendees", "allAttendees")
  .getOne();

方案2:更通用的多用户匹配方案(适合后续扩展N个用户同时匹配的场景)

如果后续需要匹配同时包含更多参会者的会话,用IN+分组计数的方式扩展性更好,不需要新增JOIN语句:

const userIds = [你的第一个用户ID, 你的第二个用户ID];
const targetConversation = await conversationRepository
  .createQueryBuilder("c")
  .innerJoin("c.attendees", "u", "u.id IN (:...userIds)", { userIds })
  // 如果需要返回会话的所有参会者信息,加下面这行
  .leftJoinAndSelect("c.attendees", "allAttendees")
  .groupBy("c.id")
  // 确保匹配到的用户数量和传入的用户数量一致,避免只匹配到其中一个用户的会话
  .having("COUNT(DISTINCT u.id) = :userCount", { userCount: userIds.length })
  .getOne();

内容的提问来源于stack exchange,提问作者Emzaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 04:09:01