RethinkDB多对多关系查询:关联实体与作者表遇问题
解决RethinkDB多表关联查询作者信息的问题
我来帮你搞定这个多表关联的问题!你现在已经成功关联了entity和entity_to_authors中间表,但还没把中间表的authorId映射到entity_authors表的实际作者信息对吧?下面给你两种可行的实现方式,按需选择:
方法一:在Merge中嵌套查询(适合单条Entity查询)
这种方式直接在你现有代码的基础上扩展,把每个entity_to_authors记录关联到对应的entity_authors记录,最终生成包含作者详情的数组:
r.table("entity") .get("f17234b6-b25c-4037-8dd1-314841967964") .merge(e -> r.hashMap("authors", // 先找到当前entity对应的所有中间表记录 r.table("entity_to_authors") .filter(entityToAuthor -> entityToAuthor.g("entityId").eq(e.g("id"))) // 把每条中间表记录转换成对应的entity_authors记录 .concatMap(entityToAuthor -> r.table("entity_authors").get(entityToAuthor.g("authorId")) ) .coerceTo("array") )) .run(connection);
这样返回的结果里,authors字段就是包含id和authorName的作者对象数组,而不是中间表的id记录了。
方法二:使用Join操作(适合批量查询或更清晰的关联逻辑)
如果需要批量查询多个Entity的作者信息,用eqJoin关联多表会更高效,逻辑也更清晰:
r.table("entity") .get("f17234b6-b25c-4037-8dd1-314841967964") // 第一步:关联entity和entity_to_authors(用entityId索引) .eqJoin("id", r.table("entity_to_authors"), {"index": "entityId"}) .zip() // 合并两个表的字段 // 第二步:关联到entity_authors表 .eqJoin("authorId", r.table("entity_authors")) .zip() // 按entity的id和title分组,把同一entity的作者归到一起 .group("id", "title") .ungroup() // 整理成最终的结构:id、title、authors数组 .map(grouped -> r.hashMap("id", grouped.g("group").nth(0)) .with("title", grouped.g("group").nth(1)) .with("authors", grouped.g("reduction").map(author -> author.pluck("id", "authorName"))) ) .run(connection);
重要优化提示
为了让关联查询更快,记得给entity_to_authors表的entityId字段创建索引:
r.table("entity_to_authors").indexCreate("entityId").run(connection);
entity_authors的id作为主键默认已经是索引,不用额外创建。
内容的提问来源于stack exchange,提问作者MadLax
相关产品推荐
相关产品推荐

