0
  • I am trying to implement relationship in Room Database using @Relation from three tables but confused with it.

  • DB consists of students, subjects and marks table.

student table:

@Entity(tableName = "student")
data class Student(
    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "student_id")
    var id: Int = 0,
    @ColumnInfo(name = "student_name")
    var name: String? = null,
    @ColumnInfo(name = "student_email")
    var email: String? = null,
    @ColumnInfo(name = "student_created_date")
    var created: Long = System.currentTimeMillis(),
    var school_id: Int = -1
)

subject table :

@Entity(tableName = "subject")
data class Subject(
    @ColumnInfo(name = "subject_id")
    var id: Int,
    @ColumnInfo(name = "subject_name")
    var name: String
)

marks table:

@Entity(tableName = "marks")
data class Marks(
    @ColumnInfo(name = "student_id")
    var stu_id: Int,

    @ColumnInfo(name = "subject_id")
    var sub_id: Int,

    @ColumnInfo(name = "marks")
    var marks: Int,
)

I want to retrieve student with their respective marks as per subject. Below is the class that I have defined but I don't know how to define relations with three tables:

data class StudentWithMarks(
    @Embedded var student: Student,
    @Relation(
        parentColumn = "student_id",
        entityColumn = "student_id"
    )
    var marks: List<Marks>
)
Sumit Shukla
  • 4,116
  • 5
  • 38
  • 57

1 Answers1

0

You can add one more columnInfo named subject_id to student table and then you can create relations between student and the subject table.

Priyanka
  • 1,791
  • 1
  • 7
  • 12