Paging And Ordering

Limit

Limit limits the query result to n entities.

  1. users, err := client.User.
  2. Query().
  3. Limit(n).
  4. All(ctx)

Offset

Offset sets the first node to return from the query.

  1. users, err := client.User.
  2. Query().
  3. Offset(10).
  4. All(ctx)

Ordering

Order returns the entities sorted by the values of one or more fields. Note that, an error is returned if the given fields are not valid columns or foreign-keys.

  1. users, err := client.User.Query().
  2. Order(ent.Asc(user.FieldName)).
  3. All(ctx)

Edge Ordering

In order to sort by fields of an edge (relation), start the traversal from the edge (you want to order by), apply the ordering, and then jump to the neighbours (target type).

The following shows how to order the users by the "name" of their "pets" in ascending order.

  1. users, err := client.Pet.Query().
  2. Order(ent.Asc(pet.FieldName)).
  3. QueryOwner().
  4. All(ctx)

Custom Ordering

Custom ordering functions can be useful if you want to write your own storage-specific logic.

The following shows how to order pets by their name, and their owners’ name in ascending order.

  1. names, err := client.Pet.Query().
  2. Order(func(s *sql.Selector) {
  3. // Join with user table for ordering by owner-name and pet-name.
  4. t := sql.Table(user.Table)
  5. s.Join(t).On(s.C(pet.OwnerColumn), t.C(user.FieldID))
  6. s.OrderBy(t.C(user.FieldName), s.C(pet.FieldName))
  7. }).
  8. Select(pet.FieldName).
  9. Strings(ctx)