AssociationAggregate

An AssociationAggregate is able to compute aggregated values from a population of associated records.

For example:

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

let bookCount = Author.books.count // AssociationAggregate<Author>

Association aggregates can be used in the annotated(with:) and having(_:) request methods:

let request = Author.annotated(with: bookCount)
let request = Author.having(bookCount >= 10)

The RowDecoder generic type helps the compiler prevent incorrect use of aggregates:

// Won't compile because Fruit is not Author.
let request = Fruit.annotated(with: bookCount)
  • Returns an aggregate that is selected in a column with the given name.

    For example:

    let aggregate = Author.books.count.forKey("numberOfBooks")
    let request = Author.annotated(with: aggregate)
    if let row = try Row.fetchOne(db, request) {
        let numberOfBooks: Int = row["numberOfBooks"]
    }