I'm working on an image-like, one-to-many database.
To explain the flow of functions, WorkoutSetInfo is added to the list whenever the Add button is pressed. (It is not inserted into DB.)
Finally, when the Save button is pressed, the Workout and WorkoutSetInfo list are inserted into the DB.
I have completed setting up the relationship between Workout and WorkoutSetInfo, but I don't know how to match the ID of each Workout with Id(parendWorkoutId) of WorktoutSetInfo.
(Now, all IDs of parendWorkoutId are set to 1.)
How should I set it up?
Workout
@Entity
data class Workout(
@PrimaryKey(autoGenerate = true)
val workoutId: Long,
val title: String = "",
var unit: String = "kg",
val memo: String = "",
)
WorkoutSetInfo
@Entity(
foreignKeys = [
ForeignKey(
entity = Workout::class,
parentColumns = arrayOf("workoutId"),
childColumns = arrayOf("parentWorkoutId"),
onDelete = ForeignKey.CASCADE
)
]
)
data class WorkoutSetInfo(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val set: Int,
var weight: String = "",
var reps: String = "",
val parentWorkoutId: Long = 1 // How do I set this up?
)
WorkoutWithSets
data class WorkoutWithSets(
@Embedded val workout: Workout,
@Relation (
parentColumn = "workoutId" ,
entityColumn = "parentWorkoutId"
)
val sets: List<WorkoutSetInfo>
)
Repository
class WorkoutRepository(private val workoutDao : WorkoutDao, title: String) {
val workout = Workout(0, title)
private val setInfoList = ArrayList<WorkoutSetInfo>()
fun add() {
val item = WorkoutSetInfo(set = setInfoList.size + 1)
setInfoList.add(item)
}
fun delete() {
if(setInfoList.size != 0)
setInfoList.removeLast()
return
}
fun save() {
workoutDao.insertWorkout(workout)
workoutDao.insertSetInfoList(setInfoList)
}
}
