Search code examples
androidkotlinandroid-room

Room creating three or four relationship between tables


I am trying to achieve the following:

enter image description here

I am working with Android Room.

In code:

@Entity(tableName = "BookReadingSchedule")
data class BookReadingSchedule(
    @PrimaryKey
    @ColumnInfo(name = "schedule_id")
    val id: Long = 0,
    val name: String = ""
)

@Entity(tableName = "Books")
data class Books(
    @PrimaryKey
    @ColumnInfo(name = "book_id")
    val id: Long = 0,
    val title: String = ""
)

@Entity(
    tableName = "BooksToRead"
    foreignKeys = [
        ForeignKey(
            entity = BookReadingSchedule::class,
            parentColumns = ["BookReadingSchedule_id"],
            childColumns = ["to_book_id"],
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
    ]
)
data class BooksToRead(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: Long = 0,
    val title: String = ""
    @ColumnInfo(name = "to_book_id", index = true)
    val book_id: Long,
)

Trying to create this relationship, but, I am not sure whether this is entirely correct or not. I have worked with LINQ C# in MS, but, never done this much on Android. I am using Kotlin.

Links I checked (before I posted here):


EDIT: Idea is that for every schedule, there will be only a handful of books that were select to be included within that schedule.


Solution

  • Your @ColumnInfo(name = "schedule_id") should be parentColum for the corresponding table. So you will need something like this

    @Entity(
        tableName = "BooksToRead"
        foreignKeys = [
            ForeignKey(
                entity = BookReadingSchedule::class,
                parentColumns = ["schedule_id"],
                childColumns = ["to_schedule_id"],
                onDelete = ForeignKey.CASCADE,
                onUpdate = ForeignKey.CASCADE
            ),
            ForeignKey(
                entity = Books::class,
                parentColumns = ["book_id"],
                childColumns = ["to_book_id"],
                onDelete = ForeignKey.CASCADE,
                onUpdate = ForeignKey.CASCADE
            )
        ]
    )