Ent: Changing where's conditions dynamically

Created on 16 Feb 2021  路  3Comments  路  Source: ent/ent

In the documentation, I found examples like this one

n, err := client.User.
    Update().
    Where(
        user.Or(
            user.AgeEQ(30),
            user.Name("bar"),
        ), 
        user.HasFollowers(),
    ).
    SetName("foo"). 
    Save(ctx) 

In some cases, I need to use some of these conditions

  • user.AgeGT(30)
  • user.AgeLT(60)
  • user.AgeGT(30) and user.AgeLT(60)

May I change the where's conditions dynamically?

thanks a lot for your suggestions :)

Question

Most helpful comment

Hey @juanpabloaj, if you work with a8m/rql, you can do it today as follows:

param, err := parser.Parse(...)
// ...
client.User.Query().
    Where(func(s *sql.Selector) {
        s.Where(sql.ExprP(p.FilterExp, p.FilterArgs...))
    }).
    All(ctx)

I'll add examples to https://github.com/a8m/rql soon.

All 3 comments

Hello @juanpabloaj 馃榾

In some cases, I need to use some of these conditions

  • user.AgeGT(30)
  • user.AgeLT(60)
  • user.AgeGT(30) and user.AgeLT(60)

May I change the where's conditions dynamically?

The Where(Predicate[T]) function accepts predicate of type T, so in your case, you can just do the following:

updater := client.User.Update().SetName("foo")
if A {
    updater.Where(user.AgeGT(30))
}
if B {
    updater.Where(user.AgeLT(60))
}
// If the 2 branches above are true, the result will be `age > 30 AND age < 60`.
n, err := updater.Save(ctx)

Does it answer your question?

@a8m thanks for the answer (and for ent 馃槃 )

Yes, that could be a solution.

Is there any plan for the future to add to this project some features similar to rql?

Like receive a string query and call to the database using ent.

https://github.com/a8m/rql#simple-example

My question is because in many cases I have a similar situation, how to create filters for an HTTP API?
Or how to pass an HTTP API query to the ORM? (without adding too much code).

Thanks again.

Hey @juanpabloaj, if you work with a8m/rql, you can do it today as follows:

param, err := parser.Parse(...)
// ...
client.User.Query().
    Where(func(s *sql.Selector) {
        s.Where(sql.ExprP(p.FilterExp, p.FilterArgs...))
    }).
    All(ctx)

I'll add examples to https://github.com/a8m/rql soon.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

errorhandler picture errorhandler  路  4Comments

rotemtam picture rotemtam  路  4Comments

ernado picture ernado  路  5Comments

dom3k picture dom3k  路  4Comments

a8m picture a8m  路  5Comments