swiftdata relationship xcode15b3 ios17

I can't find a way to make this relationship, Anyone to tell me what am i doing wrong please ?

import SwiftUI
import SwiftData

@Model class Model1 {
    @Attribute(.unique) var id:String
    var date:Date
    @Relationship(.cascade) var model2:[Model2]
    init() {
        self.id = UUID().uuidString
        self.date = Date()
        self.model2 = []
    }
}

@Model class Model2 {
    @Attribute(.unique) var id:String
    var date:Date
    @Relationship(inverse: \Model1.model2) var model1:Model1
    init(
        model1:Model1
    ) {
        self.id = UUID().uuidString
        self.date = Date()
        self.model1 = model1
    }
}

struct view1:View {
    @Environment(\.modelContext) private var db
    var body: some View {
        Text("TapMe")
            .onTapGesture {
                let m1 = Model1()
                db.insert(m1)
                let m2 = Model2(model1: m1)
                db.insert(m2)
            }
    }
}

Error :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'm1' between objects in different contexts (source = <NSManagedObject: 0x280b253b0> (entity: Model2; id: 0x282896ca0 <x-coredata:///Model2/tCB971C15-AFE3-46A2-A1FB-E688E0EF2ABF207>; data: {
    date = "2023-07-10 20:22:56 +0000";
    id = "625B994D-24BB-4935-A438-8AA6522C0FE1";
    m1 = nil;
}) , destination = <NSManagedObject: 0x280b250e0> (entity: Model1; id: 0x2828eaa40 <x-coredata:///Model1/tCB971C15-AFE3-46A2-A1FB-E688E0EF2ABF206>; data: {
    date = "2023-07-10 20:22:56 +0000";
    id = "BA3E6CF3-67EC-41CA-A150-E66E0D7226B2";
    m2 =     (
    );
}))'
Answered by milutz in 758638022

Currently it only seems to work, if the model1 relationship in Model2 is optional and only set after the insert:

[...]
let m2 = Model2()
db.insert(m2)
m2.model1 = m1
[...]
db.save()

See also here and here. I filed FB12363892 for that back in beta 1, but no reaction so far.

Accepted Answer

Currently it only seems to work, if the model1 relationship in Model2 is optional and only set after the insert:

[...]
let m2 = Model2()
db.insert(m2)
m2.model1 = m1
[...]
db.save()

See also here and here. I filed FB12363892 for that back in beta 1, but no reaction so far.

swiftdata relationship xcode15b3 ios17
 
 
Q