1

I am using Android Room, and i have to use the relationships with more than one child. I have to do the same thing explained in this question, with the same schema, (How to create a table with a two or more foreign keys using Android Room?) but using @Relationship instead of @ForeignKey.

I need this because i have to be able to access to the children from the father, without any query.

I looked in the documentation, but they only explain the case with a child (https://developer.android.com/training/data-storage/room/relationships#nested-relationships).

Could someone help me?

Thank you for your patience and help!

qwerty123
  • 43
  • 4

1 Answers1

0

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.

MikeT
  • 51,415
  • 16
  • 49
  • 68