SwiftData relationships

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.

  1. In the “Vegetable” class, why is the field “notes” an array of type Notes?
  2. Again in the “Vegetable” class does the field “notes” get stored in the database, if so what is stored?
  3. 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.

In the “Vegetable” class, why is the field “notes” an array of type Notes?

You may have several notes, so it is logical to get them in an array. What else did you think about ?

 

Again in the “Vegetable” class does the field “notes” get stored in the database, if so what is stored?

By default, all non-computed attributes are stored. Unless you use the @Transient macro.

 

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.

With @Relationship, SwiftData knows what needs to be saved to be able to rebuild the relations when needed. This tutorial should give you some insight.

SwiftData relationships
 
 
Q