doc/md: custom ordering example

This commit is contained in:
Ariel Mashraki
2021-03-29 15:05:26 +03:00
committed by Ariel Mashraki
parent 21989f4aa4
commit c9f66cd3b4
2 changed files with 19 additions and 13 deletions

View File

@@ -48,4 +48,22 @@ users, err := client.Pet.Query().
Order(ent.Asc(pet.FieldName)).
QueryOwner().
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.
```go
names, err := client.Pet.Query().
Order(func(s *sql.Selector) {
// Join with user table for ordering by owner-name and pet-name.
t := sql.Table(user.Table)
s.Join(t).On(s.C(pet.OwnerColumn), t.C(user.FieldID))
s.OrderBy(t.C(user.FieldName), s.C(pet.FieldName))
}).
Select(pet.FieldName).
Strings(ctx)
```

View File

@@ -102,26 +102,14 @@ users := client.User.
s.Where(sqljson.HasKey(user.FieldURL, sqljson.Path("Scheme")))
})).
AllX(ctx)
```
Also It can be used in subquery case, for example:
```sql
SELECT DISTINCT `todos`.`id`, `todos`.`text`, `todos`.`done`
FROM `todos` WHERE `todos`.`user_id` IN (
SELECT `id` FROM `users` WHERE `users`.`id` IN (?, ?)
)
```
```go
todos := client.Todo.Query().
Where(func(s *sql.Selector) {
t := sql.Table(user.Table)
s.Where(
sql.In(
s.C(todo.FieldUserID),
sql.Select(t.C(user.FieldID)).From(t).Where(sql.In(t.C(user.FieldID), ids...)),
sql.Select(t.C(user.FieldID)).From(t).Where(sql.In(t.C(user.FieldName), names...)),
),
)
}).