How can I represent a many to many relation with Android Room?

后端 未结 6 1123
闹比i
闹比i 2020-11-28 02:58

How can I represent a many to many relation with Room? e.g. I have \"Guest\" and \"Reservation\". Reservation can have many Guest and a Guest can be part of many Reservation

6条回答
  •  独厮守ぢ
    2020-11-28 03:35

    Based on the answer above: https://stackoverflow.com/a/44428451/4992598 only by keeping separate field names between entities you can have models returned (not just ids). All you need to do is:

    @Entity data class ReservationGuest(
        @PrimaryKey(autoGenerate = true) val id: Long,
        val reservationId: Long,
        @Embedded
        val guest: Guest
    )
    

    And yes entities can be embedded in one another as long as you don't keep duplicate fields. So in consequence the ReservationWithGuests class can look like this.

    data class ReservationWithGuests(
        @Embedded val reservation:Reservation,
        @Relation(
            parentColumn = "id",
            entityColumn = "reservationId",
            entity = ReservationGuest::class,
            projection = "guestId"
        ) val guestList: List
    )
    

    So at this point you can use val guestIdList: List because your ReservationGuest entity actually maps ids with entity models.

提交回复
热议问题