mirror of
https://github.com/ent/ent.git
synced 2026-04-28 05:30:56 +03:00
doc/md: custom ordering example
This commit is contained in:
committed by
Ariel Mashraki
parent
21989f4aa4
commit
c9f66cd3b4
@@ -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)
|
||||
```
|
||||
@@ -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...)),
|
||||
),
|
||||
)
|
||||
}).
|
||||
|
||||
Reference in New Issue
Block a user