Objection.js: Mixing eager algorithms in a single query

Created on 18 Jan 2019  Â·  2Comments  Â·  Source: Vincit/objection.js

Hey there! Thanks for Objection 😄

As a feature request, it could be great to use multiple eager algorithms in a query in order to handle a number of joins in the fewest possible queries while preserving result limits.

The goal is to apply JoinEagerAlgorithm to BelongsToOne/HasOne associations, and WhereInEagerAlgorithm to my HasMany relations.

As a simple example, with the relations:

  1. User 1 - 1 Package
  2. User 1 - 1 Contract
  3. User 1 - 1 UserSettings
  4. User 1 - n Widgets

it'd help me greatly to do something like:

User.query()
    .mergeJoinEager("[package, contract, userSettings]")
    .mergeEager("[widgets]");

and issue 2 queries to the database as opposed to 5 with the default WhereInEagerAlgorithm or losing the ability to limit if using JoinEagerAlgorithm for a single query (in my real-world case this'd actually be 6 queries instead of 18 – a meaningful impact on performance!)

Apologies if this is already possible and I've somehow missed it! Have a great weekend :v:

Most helpful comment

I once tried to implement a hybrid eager algorithm that would use joins for 1-1 relations just like that, but It ended up being too difficult and I gave up :smile: Maybe I'll give it a shot again one day.

All 2 comments

There's no way to do tha exactly like you suggested, but this performs the same amount of queries and should work:

const users = await User.query()
    .mergeJoinEager("[package, contract, userSettings]")

await User.loadRelated(users, 'widgets')

loadRelated uses the normal eager and then assigns the relations to the users.

I once tried to implement a hybrid eager algorithm that would use joins for 1-1 relations just like that, but It ended up being too difficult and I gave up :smile: Maybe I'll give it a shot again one day.

Was this page helpful?
0 / 5 - 0 ratings