vapor / fluent

Vapor ORM (queries, models, and relations) for NoSQL and SQL databases
https://docs.vapor.codes/4.0/fluent/overview/
MIT License
1.32k stars 172 forks source link

Sorting children via eager loading #721

Open aronbudinszky opened 3 years ago

aronbudinszky commented 3 years ago

Is your feature request related to a problem? Please describe.

When loading the children of a parent model, it would useful to enable sorting (and perhaps other modifications of the query) so that the response order is correct "out of the box".

Using the Star/Planet example from Vapor docs - we may want to sort planets in a Star by distance from the star:

Star.query(on: req.db).with(\.$planets)

...however this will not sort by our desired parameter, but by whatever default order the db engine returns.

Describe the solution you'd like

An obvious candidate would be the with() method:

Star.query(on: req.db).with(\.$planets, sort: \Planet.$distance)

Additionally it could take an array to provide multiple sorting options (though I suppose in the case of planets and stars this makes little sense:

Star.query(on: req.db).with(\.$planets, sort: [\Planet.$distance, ...])

A bit of complication/ugliness with the proposed API is that we also need the option to specify ASC or DESC. So, it would need to look like so (or something similar...maybe tuple, maybe enum w/ associated val):

Star.query(on: req.db).with(\.$planets, sort: Sort(\Planet.$distance, .asc))

Describe alternatives you've considered

Also thought about giving full control over the relationship query. So, something like:

Star.query(on: req.db).with(\.$planets, query: {
    $0.sort(\.$distance)
})

Ultimately I don't think this is the right approach because it could allow filtering, paginating, etc. all of which would change the result in very unexpected ways.

Additional context

None.

aronbudinszky commented 3 years ago

This somewhat relates to https://github.com/vapor/fluent/issues/712 in that this is also requesting that we can "modify" the eager loading query.