SwiftData self-referencing model has wierd behavior

I have a model like this:

@Model
final class TreeNodeModel{
    
    var createdAt: Date
    var title: String
    var content: String
    
    //Relations
    @Relationship(deleteRule:.cascade) var children: [TreeNodeModel]?
    
    init(title:String,content:String = "",) {
        self.title = title
        self.content = content
    }
}

When I try to insert models like below (works well):

let parent = TreeNodeModel(title: "parent")
let child = TreeNodeModel(title: "child")
parent.children!.append(child)
modelContext.insert(parent)

But if try to insert models like below (wierd things happened): not only parent has one children [child], child also has one children [parent]

let parent = TreeNodeModel(title: "parent")
modelContext.insert(parent)
let child = TreeNodeModel(title: "child")
parent.children!.append(child)

This is quit wierd, anyone has met this kind of issue?

I have been trying to do something similar. I think you may need an inverse to the children collection. This is what I have done and it seems to work.

If someone else knows better I'd be delighted to be schooled otherwise :-)

import Foundation
import SwiftData

@Model
final class TreeNodeModel{
    
    var createdAt: Date
    var title: String
    var content: String
    
    // Parental relationship
    public var parent: TreeNodeModel?
    
    // Inverse
    @Relationship(deleteRule:.cascade, inverse: \TreeNodeModel.parent) var children: [TreeNodeModel]?
    
    init(title: String, content: String = "") {
        self.title = title
        self.content = content
    }
}

I did the same as you did AndrewGWalsh. It has also worked well for me but sometimes, when adding new fields to my model and configuring a new schema it breaks completely.

For now I think this is the best way of doing it. I hope it will change tho.

SwiftData self-referencing model has wierd behavior
 
 
Q