Search code examples
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
    
    • assuming User is the table name (so change this accordingly)
    • there is no need to get the related Pets as they are just children of the one User.
    • this would be the more efficient as the underlying Pets table does not need to be accessed. However, if you are already retrieving the UserWithPets then it would be less efficient to invoke a second query.