swiftswiftdataswift-data-relationship

SwiftData - How to build the multiple-to-multiple relationship between two data models?


Suppose I want to built Student and Course data models, and I want that each student is registered with multiple courses and each course contains multiple students. What should I do?

Here is what I have for now:

@Model
class Student {
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \Course.students) var courses: [Course]
    
    init(name: String, courses: [Course]) {
        self.name = name
        self.courses = courses
    }
}

@Model
class Course {
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \Student.courses) var students: [Student]
    
    init(name: String, students: [Student]) {
        self.name = name
        self.students = students
    }
}

And this shows the error: Circular reference resolving attached macro 'Relationship' .


Solution

  • With the deleteRule you’ve written, you’re saying that when a Course is deleted, you want all of its Students to be deleted. And then when those Students are deleted, each of their Courses are deleted. No wonder that the compiler complains!

    You almost certainly want .nullify here, not .cascade. It’s perfectly reasonable to have Courses that nobody has signed up for yet, and Students who haven’t registered for classes yet.

    Don’t specify both relationships. By specifying the inverse of the first one, you implicitly define the second one.