Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add when to query builder #277

Closed
josephmancuso opened this issue Dec 21, 2020 · 4 comments · Fixed by #280
Closed

Add when to query builder #277

josephmancuso opened this issue Dec 21, 2020 · 4 comments · Fixed by #280
Labels
easy These issues are geared for people who have not yet contributed to this project yet Query Builder Related to the query builder

Comments

@josephmancuso
Copy link
Member

We should be able to specify a when method that receives a conditional and then optionally calls the lambda or function callback:

Example:

age = 25

User.when(age >= 18, lambda q: q.where('age_restricted', 1))
@josephmancuso josephmancuso changed the title Add when to query builder Add when to query builder Dec 21, 2020
@josephmancuso josephmancuso added Query Builder Related to the query builder easy These issues are geared for people who have not yet contributed to this project yet labels Dec 21, 2020
@Marlysson
Copy link
Contributor

Is it like a chain of where methods?

@josephmancuso
Copy link
Member Author

josephmancuso commented Dec 24, 2020

yeah it can be chained. Its just if the first parameter is truthy then run the callback in the second parameter. Would look something like this:

# QueryBuilder

def when(conditional, callback):
    if conditional:
        callback(self)
    return self

@Marlysson
Copy link
Contributor

Marlysson commented Dec 24, 2020

A doubt, the attribute "age" in "when" method... is it evaluate from conditional from outside model or every line that checks every line from User model where age it's >= 18 and in case truthy then run callback method?

@josephmancuso
Copy link
Member Author

josephmancuso commented Dec 24, 2020

No its just a normal conditional. Maybe a more obvious use case is:

def show(self, request: Request):
    User.when(self.request.input('age') >= 18, lambda q: q.where('age_restricted', 1)).get()

Its just true or false, removing the variables will just look like this:

User.when(True, lambda q: q.where('active', 1)).get()
# SELECT * FROM `users` WHERE `active` = '1'

User.when(False, lambda q: q.where('active', 1)).get()
# SELECT * FROM `users`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
easy These issues are geared for people who have not yet contributed to this project yet Query Builder Related to the query builder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants