Skip to content

Eager loading counts of related models #5526

Closed

Description

@geoffreak

I can't seem to figure out the best way to eager load the count of a related model. For example, if an account has subscriptions, how should you load the number of subscriptions on the account without having to select all subscriptions?

The best workaround I've been able to come up with is something like this:

@models.account.findAll
  include:    [
    model:      @models.subscription
    as:         'Subscriptions'
    attributes: ['id']
    required:   false
  ]

There doesn't seem to be any way to just get a subscription count without having to select at least one field to return from the query. Is there a way just to return a count?

Activity

  1. mickhansen commented on Mar 7, 2016

    @mickhansen
    Contributor

    Not when using includes. Aggregates and includes/joins are generally tricker.
    Usually what works best, atleast for PG, are window functions so you don't get those pesky aggregation errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions