One to Many Relationship in SwiftData

Hi,

I understand how to make one to many relationship in SwiftData and how to show the child records, like all cities of a country. But how to navigate and show the parent record from a child record, Like I want to show a country of a city ?

like country.cities show all cities of a country, will cities.country work to show the country ? like cities.country.name ?

Kind Regards

Not cities.country.name but if you have a single city obj selected then city.country.name will work

I tried the code below, with SiftData models also below, but I got the error .. Value of type Sight has no member destination !

ForEach (destination.sights) { sight in
                    VStack {
                        Text(sight.name)
                        Text(sight.destination.name)
            }
 }


@Model
class Destination {
    var name: String
    var details: String
    var date: Date
    var priority: Int
    @Relationship(deleteRule: .cascade) var sights = [Sight]()

    init(name: String = "", details: String = "", date: Date = .now, priority: Int = 2) {
        self.name = name
        self.details = details
        self.date = date
        self.priority = priority
    }
}


@Model
class Sight {
    var name: String
    init(name: String) {
        self.name = name
    }
}

@joadan Aha you mean we should explicitly add Destination to Sight in above code ? it won't be implicitly implemented ? that way yes it worked.

One to Many Relationship in SwiftData
 
 
Q