AssociationAggregate
public struct AssociationAggregate<RowDecoder>
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.aliased("numberOfBooks") let request = Author.annotated(with: aggregate) if let row = try Row.fetchOne(db, request) { let numberOfBooks: Int = row["numberOfBooks"] }
Declaration
Swift
@available(*, deprecated, renamed: "forKey(_:﹚") public func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
-
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"] }
Declaration
Swift
public func forKey(_ key: String) -> AssociationAggregate<RowDecoder>
-
Returns an aggregate that is selected in a column named like the given coding key.
For example:
struct AuthorInfo: Decodable, FetchableRecord { var author: Author var numberOfBooks: Int static func fetchAll(_ db: Database) throws -> [AuthorInfo] { let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks) let request = Author.annotated(with: aggregate) return try AuthorInfo.fetchAll(db, request) } }
Declaration
Swift
@available(*, deprecated, renamed: "forKey(_:﹚") public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
-
Returns an aggregate that is selected in a column named like the given coding key.
For example:
struct AuthorInfo: Decodable, FetchableRecord { var author: Author var numberOfBooks: Int static func fetchAll(_ db: Database) throws -> [AuthorInfo] { let aggregate = Author.books.count.forKey(CodingKeys.numberOfBooks) let request = Author.annotated(with: aggregate) return try AuthorInfo.fetchAll(db, request) } }
Declaration
Swift
public func forKey(_ key: CodingKey) -> AssociationAggregate<RowDecoder>