Search code examples
javaandroidkotlinandroid-roomandroid-room-relation

Android Room getting count of elements in an 'incoming foreign key list' in an 'embedded entity'?


I have 2 Entities, Grade and Student, Student is having a foreign key towards the class room. Embedded entity ClassRoom looks like this,

data class ClassRoom(

    @Embedded
    val level: ClassLevel

    @Relation(
        parentColumn = "id",
        entityColumn = "ClassLevel"
    )
    val students: List<Student>,

    // val strength: Int ?

) 

What I am trying to achieve is, using ClassRoomInstance.strength to get the count of incoming foreign keys. Than calculating the sizes of students with students.size

What is the way to achieve this?

Thanks


Solution

  • You can create a query that returns the student count.

    Consider the following POJO's, a Movie and Trailers

    @Entity
    data class Movie(
        @PrimaryKey
        val id: Int,
        val title: String,
        val overview: String
    )
    
    @Entity
    data class Trailer(
        @PrimaryKey
        val id: Int,
        val movieId: Int,
        val trailerPath: String
    )
    

    Imagine that I want to get the Movie with the trailers count

    data class MoviesWithTrailerCount(
        @Embedded
        val movie: Movie,
        val trailerCount: Int
    )
    

    In the MovieDAO, I can create a query:

    @Transaction
    @Query("SELECT M.*, COUNT(T.id) AS trailerCount FROM Movie M INNER JOIN Trailer T ON T.movieId = M.id WHERE M.id = :id")
    abstract suspend fun moviesAndTrailersCount(id: Int): MoviesWithTrailerCount
    

    So, basically what you want to achieve can be done using SQL queries and @Embedded