Post

Replies

Boosts

Views

Activity

Reply to SwiftData Relationship
Your relationship should have a reference to the model(s) on both sides. Looks like you're missing a property on the Child model to refer to the Main model. I think you need the inverse attribute on your relationship on Main to identify the property I've only been able to get it to work if both sides of the relationship are optionals, even if the relationship is mandatory. So you need an optional trans array rather than an empty array. You'd create or fetch an instance of the Main model first, before creating the Child instances. Then create the Child instances, passing in a reference to their parent. You don't have to use an optional in the Child initializer to avoid accidentally leaving it nil. @Model final class Main { var name: String var limit: Double @Relationship(deleteRule: .cascade, inverse: \Child.parent) var trans: [Child]? init(name: String, limit: Double) { self.name = name self.limit = limit } } @Model final class Child { var trip: String var distance: Double var parent: Main? init(trip: String, distance: Double, parent: Main) { self.trip = trip self.distance = distance self.parent = parent } } let parent = Main(name: "", limit: 0) let child1 = Child(trip: "", distance: 0, parent: parent) let child2 = Child(trip: "", distance: 0, parent: parent) modelContext.insert(parent) modelContext.insert(child1) modelContext.insert(child2) modelContext.save() // the next time you fetch the parent, the children will be present in the `trans` array try modelContext.fetch(FetchDescriptor<Main>()) // or if you need them immediately in the code you're executing, you can assign them: parent.trans = [child1, child2]
Oct ’23