I am new to Swift, and I am trying to get a grip on SwiftData, which SO FAR seems pretty straightforward EXCEPT relationships between tables. I come from a MYSQL, SQLITE3 background and I am used to “Primary Keys”, Inner and Outer Joins, One-to-One and One-to-Many relationships. Which SwiftData does not appear to do (I think).
I am following several reasonably good online tutorials on the subject, all of which gloss over how relationships work. The best one is a table for vegetables alongside a table of notes for each vegetable (A one-to-many relationship). The classes we set up for the schemas are as follows.
import Foundation
import SwiftData
@Model
class Vegetable {
var name: String
@Relationship(deleteRule: .cascade) var notes: [Note]?
init(name: String) {
self.name = name
}
}
@Model
class Note {
var text: String
var vegetable: Vegetable?
init(text: String) {
self.text = text
}
}
I can’t comprehend how they work. None of the tutorials I have watched explain it or explain it in a way I can understand.
- In the “Vegetable” class, why is the field “notes” an array of type Notes?
- Again in the “Vegetable” class does the field “notes” get stored in the database, if so what is stored?
- In the “Note” Class it looks like the whole of the class “Vegetable” gets stored in the variable “vegetable”, which may or may not get stored in the database.