Search code examples
androidrelational-databaseandroid-roomandroid-room-relation

Android Room Relation returns an invalid list


I have a query with a complex relation.

data class GameWithHouseworkResult(
    @Embedded val game:GameClass,
    @Relation(
            entity = GameHouseworkResult::class,
            parentColumn = "gameId",
            entityColumn = "houseworkId" ,
            associateBy = Junction(value=GameHouseworkResult::class)
    )
    val houseworkAndResult: List<HouseworkAndResult>
)

I have 3 entities and one additional class

    @Entity
    class GameClass(
        @PrimaryKey(autoGenerate = true)
        var gameId: Int = 0,
        val mainPlayer:String,
        var secondPlayer:String=""
    }
    
    @Entity
    data class HouseworkClass(
        @PrimaryKey
        val houseworkId: Int,
        val name:String,
        val score:Int
        ) {
    }
    
    @Entity(primaryKeys = ["gameId", "houseworkId"])
    class GameHouseworkResult(
        var gameId: Long,
        val houseworkId:Long,
        val userToken:String,
        val isDone:Boolean?= null) {
    }

data class HouseworkAndResult(
    @Embedded val gameHouseworkResult:GameHouseworkResult,
    @Relation(
        parentColumn = "houseworkId",
        entityColumn = "houseworkId"
    )
    val housework: HouseworkClass
)

GameHouseworkResult is a binder class, it contains the following data enter image description here

    @Transaction
    @Query("SELECT * FROM GameClass where gameId=:id")
    suspend fun getGameWithHouseworkResult(id:Long): GameWithHouseworkResult

when I send a request with gameId = 26, I should get a list(houseworkAndResult) with five elements, but I get a list of 10 elements, and each one says that gameId = 26. Most likely this is due to the same houseworkId, but I cannot understand where I went wrong when drawing up the relations. Please HELP me!


Solution

  • Don't worry, I've found a solution. I confused the @relation and used many-to-many instead of one-to-many. Correct code

    data class GameWithHouseworkResult(
        @Embedded val game:GameClass,
        @Relation(
                entity = GameHouseworkResult::class,
                parentColumn = "gameId",
                entityColumn = "gameId"
        )
        val houseworkAndResult: List<HouseworkAndResult>
    )