androidandroid-roomandroid-room-relation

Android Room Relations get limited fields from embedded model


I have a model like that

class UserWithPets {
    @Embedded
    var user: User? = null

    @Relation(
        parentColumn = "id",
        entityColumn = "userId"
    )
    var pets: List<Pet> = ArrayList()
}

with models

data class User(
   val id: String,
   val age: Int
)

data class Pet(
   val id: String,
   val userId: String,
   val name: String
)

Every works like a charm, but the thing is I only want to get the age of the user and not the whole model. Is there a way to achieve that while keeping embedded and relation annotation ? Or should i make a custom query to get only the field I want from the user model?


Solution

  • You can either get the age from the retrieved UserWithPets object or you can use:-

    @Query("SELECT age FROM User WHERE id=:userId")
    fun getUsersAge(userId: String): Int