Hello, I have the problem that my todos are not only assigned to one project (one-to-many). They are displayed in the same way in every project. What have I done wrong?
Die HauptApp:
import SwiftData
@main
struct consiliaApp: App {
var body: some Scene {
WindowGroup {
ProjektView()
}.modelContainer(for: Projekte.self)
}
}
Das Datenmodell:
import SwiftData
@Model
final class Projekte {
var name: String
var info: String
var startdate: Date
var enddate: Date
var startadresse: String
var zieladresse: String
var priority: Int
@Relationship(deleteRule: .cascade, inverse: \Todo.projekte)
var todos: [Todo]? = []
init(name: String, info: String, startdate: Date, enddate: Date, startadresse: String, zieladresse: String, priority: Int) {
self.name = name
self.info = info
self.startdate = startdate
self.enddate = enddate
self.startadresse = startadresse
self.zieladresse = zieladresse
self.priority = priority
}
}
@Model
class Todo {
var name: String
// @Relationship
var projekte: Projekte?
init(name: String, projekte: Projekte) {
self.name = name
self.projekte = projekte
}
}
So speichere ich die Projekte:
let newDaten = Projekte(name: name, info: info, startdate: stardate, enddate: enddate, startadresse: startadresse, zieladresse: zieladresse, priority: priority)
modelContext.insert(newDaten)
newDaten.todos = []
Das ist der TodoAddView:
import SwiftData
struct TodoAddView: View {
@Environment(\.modelContext) private var modelContext
@Environment(\.dismiss) var dismiss
var projekte: Projekte
@State private var name: String = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("Name")) {
TextField("Name eingeben", text: $name)
}
}
.navigationBarTitle("Aufgabe hinzufügen", displayMode: .inline)
.navigationBarItems(leading: Button("Abbrechen"){
dismiss()
}.foregroundStyle(.red), trailing: Button("Fertig") {
// Hier Code zum Speichern der Daten
let newDaten = Todo(name: name, projekte: projekte)
modelContext.insert(newDaten)
newDaten.projekte = projekte
projekte.todos?.append(newDaten)
dismiss()
})
}
}
}
Thanks and a nice Weekend!