mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
doc/md: add docs on using expression predicates in custom WHERE clauses (#2520)
* Add docs on using ExprP() for custom WHERE sql statement * Add ExprP() examples using integration test * move custom predicate example and show examples using both P() and ExprP() * fix to greater or equal than * rephrase wording and fix sql builder * Update doc/md/predicates.md Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com> * Update doc/md/predicates.md * Update doc/md/predicates.md * Update doc/md/predicates.md * Update doc/md/predicates.md Co-authored-by: Ariel Mashraki <7413593+a8m@users.noreply.github.com>
This commit is contained in:
@@ -89,6 +89,41 @@ client.Pet.
|
||||
|
||||
Custom predicates can be useful if you want to write your own dialect-specific logic or to control the executed queries.
|
||||
|
||||
For example, in order to use built-in SQL functions such as `DATE()`, use one of the following options:
|
||||
|
||||
1. Pass a dialect-aware predicate function using the `sql.P` option:
|
||||
|
||||
```go
|
||||
users := client.User.Query().
|
||||
Select(user.FieldID).
|
||||
Where(sql.P(func(b *sql.Builder) {
|
||||
b.WriteString("DATE(").Ident("last_login_at").WriteByte(')').WriteOp(OpGTE).Arg(value)
|
||||
})).
|
||||
AllX(ctx)
|
||||
```
|
||||
|
||||
The above code will produce the following SQL query:
|
||||
|
||||
```sql
|
||||
SELECT `id` FROM `users` WHERE DATE(`last_login_at`) >= ?
|
||||
```
|
||||
|
||||
2. Inline a predicate expression using the `ExprP()` option:
|
||||
|
||||
```go
|
||||
users := client.User.Query().
|
||||
Select(user.FieldID).
|
||||
Where(func(s *sql.Selector) {
|
||||
s.Where(sql.ExprP("DATE(last_login_at >= ?", value))
|
||||
}).
|
||||
AllX(ctx)
|
||||
```
|
||||
|
||||
The above code will produce the same SQL query:
|
||||
|
||||
```sql
|
||||
SELECT `id` FROM `users` WHERE DATE(`last_login_at`) >= ?
|
||||
```
|
||||
#### Get all pets of users 1, 2 and 3
|
||||
|
||||
```go
|
||||
|
||||
Reference in New Issue
Block a user