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

后端 未结 6 1115
闹比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:36

    With the introduction to Junction in room you can handle many-to-many relationship with ease.

    As @Devrim stated you can use an extra entity (ReservationGuest) which keeps the relation between Guest and Reservation(also know as associative table or junction table or join table).

    @Entity
    data class Guest(
      @PrimaryKey
      val gId: Long,
      val name: String,
      val email: String
    )
    
    @Entity
    data class Reservation(
      @PrimaryKey
      val rId: Long,
      val table: String
    )
    
    @Entity(
      primaryKeys = ["reservationId", "guestId"]
    )
    data class ReservationGuest(     
      val reservationId: Long,
      val guestId: Long
    )
    

    Now you can get reservation with guests using this model:

    data class ReservationWithGuests (
        @Embedded
        val reservation: Reservation,
        @Relation(
                parentColumn = "rId",
                entity = Guest::class,
                entityColumn = "gId",
                associateBy = Junction(
                        value = ReservationGuest::class,
                        parentColumn = "reservationId",
                        entityColumn = "guestId"
                )
        )
        val guests: List
    )
    

    You can also get guest with their list of reservations as.

    data class GuestWithReservations (
      @Embedded
      val guest: Guest,
      @Relation(
            parentColumn = "gId",
            entity = Reservation::class,
            entityColumn = "rId",
            associateBy = Junction(
                    value = ReservationGuest::class,
                    parentColumn = "guestId",
                    entityColumn = "reservationId"
            )
      )
      val reservations: List
    )
    

    Now you can query database for the result as:

    @Dao
    interface GuestReservationDao {
      @Query("SELECT * FROM Reservation")
      fun getReservationWithGuests(): LiveData>
    
      @Query("SELECT * FROM Guest")
      fun getGuestWithReservations(): LiveData>
    
    }
    

提交回复
热议问题