Skip to content

How to Fetch Associated Records with Aggregated Counts Using GRDB and ValueObservation? #1629

Answered by groue
pedrommcarrasco asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @pedrommcarrasco,

GRDB is not currently able to fetch an associated record along with aggregates. When you run a request like the one below, you face a "Not implemented" fatalError:

let request = Employee
    .including(optional: Employee.company
        .annotated(with: Company.employees.count))

Until the library learns to run such a request, you can do it in three steps:

  1. Fetch employees with their company
  2. Fetch the counts for those companies
  3. Merge both results together

ValueObservation will deal with it just fine.

Sample code (you can paste and run):

// The base records
struct Employee: Codable, FetchableRecord, PersistableRecord {
    static let company = belongsTo(Company.self)

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@pedrommcarrasco
Comment options

Answer selected by pedrommcarrasco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants