What is a good GRDB pattern for accessing properties of related objects?

33 Views Asked by At

I'm fairly new to GRDB, but I've worked with ORMs and similar object-oriented data layers in the past. I've been using GRDB with SwiftUI, and I've run into a a question I haven't found an answer for in the documentation.

Let's say I have some model objects that look like this:

struct Game {
    static let visitorTeamForeignKey = ForeignKey(["visitorTeamId"])
    static let homeTeamForeignKey = ForeignKey(["homeTeamId"])
    static let visitorTeam = hasOne(Team.self, using: visitorTeamForeignKey)
    static let homeTeam = hasOne(Team.self, using: homeTeamForeignKey)

    var visitorTeamId: String
    var visitorTeam: QueryInterfaceRequest<Team> {
        request(for: Game.visitorTeam)
    }
    
    var homeTeamId: String
    var homeTeam: QueryInterfaceRequest<Team> {
        request(for: Game.homeTeam)
    }
}

struct Team: Hashable {
    var id: String
    var logoUrl: String?
    var title: String?
    var divisionTitle: String? // translated from division object
}

I would like the Game to have a resolved description that includes the names of the teams. In order to do this from the Game itself, I would have to retrieve the teams, and to retrieve the teams I'd need a reference to the database.

What is the recommended pattern to do something like this? Is it to do a JOIN query that includes the teams and then hydrate some other object that includes all fields? Or something else?

0

There are 0 best solutions below