Android 房间:与更多人的关系 children

Android Room: Relationships with more children

我正在使用 Android 个房间,我必须使用与多个 child 的关系。我必须做这个问题中解释的同样的事情,使用相同的模式,()但使用@Relationship 而不是@ForeignKey。

我需要这个,因为我必须能够访问父亲的 children,无需任何查询。

我查看了文档,但他们只用 child (https://developer.android.com/training/data-storage/room/relationships#nested-relationships) 解释了这种情况。

有人可以帮我吗?

感谢您的耐心等待和帮助!

首先没有@Relationship代替@ForeignKey.

@ForeignKey 定义了一个约束(规则),表示 child 的列的值必须是引用中的值parent 的列,如果不是,则发生冲突。

@Relationship 定义了一种关系,Room 然后通过添加子查询来尊重 child 的所有相关实体 parent.

您可以使用两者的任意组合(none,其中之一或两者之一)。尽管 @Relationship 可能最好由 @ForeignKey 支持。

假设你想要一个 entity/table 有多个 children 那么你只需要一个 POJO 与 parent @Embedded 与多个 @Relationship's .

@Dao@Query然后只需要提取parents,获取children的工作由Room生成的代码完成.您提取 POJO objects 并且 children 将在 POJO 中 objects。

  • 请注意,您仅限于 ALL children 而不是子集,因此 WHERE 子句对获得的 children 没有影响(因此 @Relationship 概述中的大写 ALL)

如果你的意思是嵌套 children。即 parent 的 child 有它自己的 child(ren)。然后你采用分层方法。启动没有 parent(最低 child)的 child,然后为 parent(@Embedded)创建一个带有 child(ren)( @关系)。对于 parent 的 parent,您使用 @Relationship 为较低 parent 的 parent 创建一个 POJO,注意实体不是 [=55 的 POJO =] 但是相关的 objects 属于 POJO 类型的实体 BUT。

您不妨参考这个例子,这涵盖了上述两种情况。