Well, the issue seems to be that I'm not inserting the Modifier or Item into the context prior to creating a Transaction. I would only append the Modifier to the array in Item, and then I would append the Item to the array in Transaction. Once the Transaction was created, it would insert the Transaction into the context. I assumed that would insert all relevant models but I guess not.
I recall having an issue with this, because I don't want to insert the Modifier until the Transaction has been created. I believe I tried to use context.rollback() in a different application, however, it doesn't work because the Modifier is being inserted and saved. At the moment, this seems to be working for me.
First, I had to manually set a different modelContainer for the view that allows you to create a Transaction, and then disable auto-save.
.sheet(isPresented: $addTransaction, content: {
TransactionEditor()
.modelContainer(for: Transaction.self, isAutosaveEnabled: false)
})
I tested this, and it creates the models without any issues, but of course they don't get saved. So when you view ContentView(), nothing is there.
Second, in the my other editors (ItemEditor and ModifierEditor), I insert those models into the context before appending them to their specific arrays. Here is code from ModifierEditor(). This context of course being the one attached to TransactionEditor() since ModifierEditor() is in that same stack.
Button("Add") {
let modifier = Modifier(timestamp: timestamp, value: value)
context.insert(modifier)
modifiers.append(modifier)
dismiss()
}
Then, in my TransactionEditor in the button that is creating the Transaction, I did this.
Section {
Button("Add") {
let transaction = Transaction(timestamp: timestamp, note: note, items: items)
context.insert(transaction)
do {
try context.save()
} catch {
print("Could not save transaction: \(error.localizedDescription)")
}
dismiss()
}
}
That will save the transaction, and it successfully makes all relationships without having to close to reopen the application. I don't fully understand why I'm not able to only insert the Transaction. When I did it that way, it would make the relationship to the Item successfully, just not the Modifier to Item relationship. Anyways, I'm glad it seems to be working now.