我有两个应该相互连接的Realm模型,但在写入模型时我很难理解如何执行此操作。
第一个模型将始终在第二个模型之前填充。该模型包含课程名称和与课程相关的一些数据:
class CourseModel: Object {
dynamic var coursename = ""
dynamic var par3field = 0
dynamic var par4field = 0
dynamic var par5field = 0
}
第二个模型包含与课程相关的所有评分数据:
class ScoresModel: Object {
dynamic var dateplayed = ""
}
我的问题是 - 如何编写ScoresModel数据并将此数据链接到相应的CourseModel的课程名称及其相关数据?
来自bcamur的回复之后的其他内容: bcamur,谢谢你的反馈。这看起来像我需要的。但是,在将ScoresModel写入Realm时,我需要做些什么来让Realm知道哪个课程名称链接我刚才写的ScoresModel数据?
我目前正在编写这样的2个模型:
let mycourse = CourseModel()
mycourse.coursename = courseName
mycourse.par3field = par3s
mycourse.par4field = par4s
mycourse.par5field = par5s
CoursesData.addNewCourse(my course)
let dataToSave = ScoresModel()
dataToSave.dateplayed = dateTextField.text!
ScoresData.saveNewScores(dataToSave)
提前谢谢。
答案 0 :(得分:1)
您可以将ScoresModel
个对象保存为CourseModel
:
class CourseModel: Object {
dynamic var coursename = ""
dynamic var par3field = 0
dynamic var par4field = 0
dynamic var par5field = 0
let scoreModels: List<ScoresModel> = List<ScoresModel>()
}
class ScoresModel: Object {
dynamic var dateplayed = ""
//include this if you want to be able to see which course has this ScoresModel in its scoresModels list
var courseModel: CourseModel? {
return linkingObjects(CourseModel.self, forProperty: "scoreModels").first
}
}