First there is no @Relationship
instead of @ForeignKey
.
@ForeignKey
defines a constraint (rule) that says that the value of the column(s)of the child must be a value in referenced column(s) of the parent, if not then a conflict occurs.
@Relationship
defines a relationship that Room then honours by adding subqueries that get ALL of the related entities from the child for the parent.
You can have any combination of the two (none, 1 of either or both). Although an @Relationship
is probably best supported with an @ForeignKey
.
Assuming that you want an entity/table to have multiple children then you simply have a POJO with parent @Embedded
with multiple @Relationship
's.
The @Dao
's @Query
then just have to extract the parents, the work of obtaining the children is done by the code generated by Room. You extract the POJO objects and the children will be objects within the POJO.
- Note you are limited to ALL children and not a subset so WHERE clauses have no affect on what children are obtained (hence the uppercase ALL in the overview of @Relationship)
If however you mean nested children. i.e. a child of the parent has it's own child(ren). Then you take a hierarchical approach. Starting the child that has no parent (lowest child) then you create a POJO for the parent (@Embedded) with the child(ren) (@Relationship). For that parent's parent you create a POJO for the parent of the lower parent with an @Relationship NOTING that the Entity is not the POJO of the child BUT the Entity BUT that the related objects are of the type of the POJO.
You may wish to refer to this example Data classe to Room entities , this covers both scenarios described above.