Relationships are not persisted unless there is an inverse?

Hi,

I encountered the issue, that unless an inverse relationship is modelled, the relationship is not persisted. This can be reproduced with the sample code below:

  • Press the "Add Person" button twice
  • Then press the "Add group" button

You now can see that the group has to member, but once you restart the app the members a gone. Once an inverse relationship is added (see commented code) the relationships are persisted.

Any idea if this is intended behaviour?

import SwiftData
import SwiftUI

// MARK: - Person -

@Model
class Person {
  var name: String
//  uncomment to make it work @Relationship(.nullify) var group: Group?

  init(name: String) {
    self.name = name
  }
}

// MARK: - Group -

@Model
class Group {
  var name: String
//  uncomment to make it work @Relationship(.nullify, inverse: \Person.group) public var members: [Person]
  @Relationship(.nullify) public var members: [Person] // comment to make it work

  init(name: String) {
    self.name = name
  }
}

// MARK: - SD_PrototypingApp -

@main
struct SD_PrototypingApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
    .modelContainer(for: [Person.self, Group.self])
  }
}

// MARK: - ContentView -

struct ContentView: View {
  @Environment(\.modelContext) private var modelContext

  @Query private var groups: [Group]
  @Query private var persons: [Person]

  var body: some View {
    VStack {
      ForEach(groups) { group in
        Text("\(group.name): \(group.members.count)")
      }
      ForEach(persons) { person in
        Text("Person: \(person.name)")
      }
      Button {
        assert(persons.isEmpty == false)
        if groups.isEmpty {
          let group = Group(name: "Group A")
          group.members = persons
          modelContext.insert(group)
          try! modelContext.save()
        }
      } label: {
        Text("Add a group")
      }
      .disabled(!groups.isEmpty || persons.isEmpty)

      Button {
        let person = Person(name: "Person \(Int.random(in: 0 ... 1_000_000))")
        modelContext.insert(person)
      } label: {
        Text("Add Person")
      }
    }
  }
}
Relationships are not persisted unless there is an inverse?
 
 
Q