Sorting

Basics

You can add sorting criteria to your query by calling the orderBy method.

// Sort by a single field
Actor.findMany().orderBy([
{ firstName: 'ASC' },
]);
// Sort by multiple fields
Actor.findMany().orderBy([
{ lastUpdated: 'DESC' },
{ id: 'ASC' },
]);

Sort direction

The following sort directions are valid: ASC, DESC.

Sorting by related model fields

One-to-one relationships

You can sort by any of the related model's fields.

Film.findMany().orderBy([{
language: { name: 'ASC' },
}]);

One-to-many and many-to-many relationships

You can also sort by aggregate values of the related model's fields. For example, using count

Actor.findMany().orderBy([
{ films: { count: 'ASC' } },
]);

or the 'avg', 'sum', 'min' or 'max' of a field:

Actor.findMany().orderBy([
{ films: { avg: { stars: 'ASC' } } },
]);

The @orderBy directive

If you're writing a resolver, it's feasible to just transform whatever arguments you expose for the field into an object that can then be passed to the orderBy method. For example:

const orderBy = [{ [args.sortBy]: args.sortDir }]
return Actor.findMany().resolveInfo(info).orderBy(orderBy)

However, you may want to support all of the functionality shown above. In this case, you can just use the @orderBy directive to create the appropriate orderBy argument on your field for you.

type Query {
films: [Film!]! @orderBy
}
tip

If you use the resolveInfo method, you don't have to call the orderBy method at all. Sqlmancer will look for an argument named orderBy and modify your query builder appropriately.

If the type of your field is not the model you want to use to generate the orderBy argument, you can specify the model to be used.

type Query {
filmFavorites: [FilmFavorite!]! @orderBy(model: "Film")
}
tip

You can also use the @many directive instead of applying the @where, @orderBy, @limit and @offset directives separately.