Cor Brink
Cor Brink

Reputation: 79

Realm models' relationships - Swift

I have 2 Realm models that should be connected to each other but I have difficulty understanding how to do this when writing to a model.

The 1st model will always be populated before the 2nd. This model contains a course name and some data related to the course:

class CourseModel: Object {

    dynamic var coursename = ""
    dynamic var par3field = 0
    dynamic var par4field = 0
    dynamic var par5field = 0
}

The second model has all the scoring data related to the course:

class ScoresModel: Object {

    dynamic var dateplayed = ""
}

My question is this - how do i write the ScoresModel data and link this data to the appropriate CourseModel's course name and it's associated data?

ADDITIONAL AFTER ANSWER FROM bcamur: bcamur, thank you for the feedback. This looks like what I need. However, when writing the ScoresModel to Realm, what do i need to do to let the Realm know to which course name to link the ScoresModel data I just wrote?

I'm currently writing the 2 models like this:

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)

Thank you in advance.

Upvotes: 1

Views: 120

Answers (1)

bcamur
bcamur

Reputation: 894

You can save the ScoresModel objects as a list in your 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
    }
}

Upvotes: 1

Related Questions