Static Methodgrdb 7.3.0GRDB

hasMany(_:through:using:key:)

Creates a HasManyThroughAssociation between Self and the destination TableRecord type.

TableRecord+Association.swift:433
static func hasMany<Pivot, Target>(_ destination: Target.RowDecoder.Type, through pivot: Pivot, using target: Target, key: String? = nil) -> HasManyThroughAssociation<Self, Target.RowDecoder> where Self == Pivot.OriginRowDecoder, Pivot : Association, Target : Association, Pivot.RowDecoder == Target.OriginRowDecoder

Parameters

destination

The record type at the other side of the association.

pivot

An association from Self to the intermediate type.

target

A target association from the intermediate type to the destination type.

key

The association key. By default, it is the key of the target.

For example:

struct Citizen: TableRecord { }

struct Passport: TableRecord {
    static let citizen = belongsTo(Citizen.self)
}

struct Country: TableRecord {
    static let passports = hasMany(Passport.self)
    static let citizens = hasMany(Citizen.self,
                                  through: passports,
                                  using: Passport.citizen)
}

The association lets you define requests that involve both the source and the destination type.

For example, we can fetch all countries with all their citizens:

struct CountryInfo: FetchableRecord, Decodable {
    var country: Country
    var citizens: [Citizen]
}

try dbQueue.read { db in
    let request = Country
        .including(all: Country.citizens)
        .asRequest(of: CountryInfo.self)
    let countryInfos = try request.fetchAll(db)
    for countryInfo in countryInfos {
        print("\(countryInfo.country.name) has \(countryInfo.citizens.count) citizens")
    }
}

The association can also help fetching associated records:

try dbQueue.read { db in
    let country: Country = ...
    let citizens: [Citizen] = country
        .request(for: Country.citizens)
        .fetchAll(db)
}

For more information about this association, see HasManyThroughAssociation.

Methods that build requests involving associations are defined in the JoinableRequest protocol.