(Android) 如何在一对多关系中将子 ID 与父 ID 匹配

(Android) How to match child ID to parent in one-to-many relationship

我正在处理类似图像的 one-to-many 数据库。

为了解释功能流程,只要按下 Add button,就会将 WorkoutSetInfo 添加到列表中。 (It is not inserted into DB.)

最后,当按下Save button时,WorkoutWorkoutSetInfo list被插入DB

我已经完成WorkoutWorkoutSetInfo之间的关系设置,但我不知道如何将每个WorkoutID与Id匹配( parendWorkoutId) WorktoutSetInfo.

(现在parendWorkoutId的所有ID都设置为1。)

我该如何设置?


锻炼

@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>
)

存储库

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)
    }
}

workoutDaointerface/abstractclass中,有insertWorkout函数return一个Long。这将是插入的锻炼的 id-1 如果插入被忽略.

Retrieve/Use 这个 returned 值并用它来设置 setInfoList 中每个元素的 parentWorkoutId 保存函数。

  • 当然,如果值为 -1,那么您应该适当地处理它,因为不会插入锻炼。

例如

如果您将 parentWorkoutIdval 更改为 var 那么保存功能可能类似于:-

fun save(): Boolean {
    var rv = false /* indicate nothing done as insert was ignored */
    val id = workoutDao.insertWorkout(workout)
    if (id > 0) {
        rv = true
        for (wi in setInfoList) {
            wi.parentWorkoutId = id
        }
        workoutDao.insertSetInfoList(setInfoList)
    }
    return rv
}