Static Methodgrdb 7.3.0GRDB

hasMany(_:key:using:)

Creates a HasManyAssociation between Self and the destination TableRecord type.

TableRecord+Association.swift:133
static func hasMany<Destination>(_ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation<Self, Destination> where Destination : TableRecord

Parameters

destination

The record type at the other side of the association.

key

The association key. By default, it is Destination.databaseTableName.

foreignKey

An eventual foreign key. You need to provide one when no foreign key exists to the destination table, or several foreign keys exist.

For example:

struct Book: TableRecord { }
struct Author: TableRecord {
    static let books = hasMany(Book.self)
}

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

For example, we can fetch all authors with all their books:

struct AuthorInfo: FetchableRecord, Decodable {
    var author: Author
    var books: [Book]
}

try dbQueue.read { db in
    let request = Author
        .including(all: Author.books)
        .asRequest(of: AuthorInfo.self)
    let authorInfos = try request.fetchAll(db)
    for authorInfo in authorInfos {
        print("\(authorInfo.author.name) wrote \(authorInfo.books.count) books")
    }
}

The association can also help fetching associated records:

try dbQueue.read { db in
    let author: Author = ...
    let books: [Book] = author
        .request(for: Author.books)
        .fetchAll(db)
}

For more information about this association, see HasManyAssociation.

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