删除领域中的多个子对象时如何按祖父值过滤?

How to filter by grand parent value when deleting multiple child objects in realm?

我正在尝试删除与特定锻炼对象中的所有锻炼对象关联的所有 WSR 对象。

我只是在过滤掉所有 WSR 对象时遇到了一些问题。现在的设置方式是,如果我有多个 Exercise 对象,只有与第一个 Exercise 对象相关联的 WSR 值会被删除,而不会删除其余的。

如何过滤掉与特定锻炼中的所有锻炼对象关联的所有 WSR 对象?

class Days : Object {
    @objc dynamic var weekday : String = ""

    let workout = List<Workouts>()
}

class Workouts : Object {
    @objc dynamic var title : String = ""
    var parentDay = LinkingObjects(fromType: Days.self, property: "workout")

    let exercise = List<Exercises>()
}

class Exercises : Object {
    @objc dynamic var exerciseName : String = ""

    var parentWorkout = LinkingObjects(fromType: Workouts.self, property: "exercise")

    let wsr = List<WeightSetsReps>()
}

class WeightSetsReps : Object {
    @objc dynamic var weight = 0
    @objc dynamic var reps = 0
    var parentExercise = LinkingObjects(fromType: Exercises.self, property: "wsr")
}

if days?[indexPath.section].workout[indexPath.row].exercise.isEmpty == false {

    if let selectedWorkout = days?[indexPath.section].workout[indexPath.row] {
        let thisWorkoutsExercises = realm.objects(Exercises.self).filter("ANY parentWorkout == %@", selectedWorkout)
        // Filter function to get all wsr's associated with the selected workout...
        let thisWorkoutsWsr = realm.objects(WeightSetsReps.self).filter("ANY parentExercise == %@", days?[indexPath.section].workout[indexPath.row].exercise[indexPath.row])

        realm.delete(thisWorkoutsWsr)
        realm.delete(thisWorkoutsExercises)
        realm.delete((days?[indexPath.section].workout[indexPath.row])!)
    }
} else {
    realm.delete((days?[indexPath.section].workout[indexPath.row])!)
}

问题出在这一行:
let thisWorkoutsWsr = realm.objects(WeightSetsReps.self).filter("ANY parentExercise == %@", days?[indexPath.section].workout[indexPath.row].exercise[indexPath.row])

通过使用 ANY parentExercise == ... .exercise[indexPath.row]),您仅从一个索引的练习中请求 WSR。恕我直言,如果此锻炼的锻炼次数低于锻炼天数,这甚至可能会崩溃。
通过使用 ANY .. IN .. 运算符,您可以请求 exercise 数组中的所有练习。

试试这个:

    guard let workout = days?[indexPath.section].workout[indexPath.row] else { return }
    if workout.exercise.isEmpty {  
        realm.delete(workout)
        return
    }


    let thisWorkoutsExercises = realm.objects(Exercises.self).filter("ANY parentWorkout == %@", workout)
    // Filter function to get all wsr's associated with the selected workout...
    let thisWorkoutsWsr = realm.objects(WeightSetsReps.self).filter("ANY parentExercise IN %@", thisWorkoutsExercises)

    realm.delete(thisWorkoutsWsr)
    realm.delete(thisWorkoutsExercises)
    realm.delete(workout)