Hello everyone,
I use Diesel in combination with a Rocket REST API and I’m wondering how I could achieve dynamic filtering.
For simplicity let’s assume I have to requests:
example.com/example?title=myexample
example.com/example?title=myexample&description=helloworld
The first request contains just a title and the second one a title + description:
The ideal query 1 would now look like:
SELECT * FROM example WHERE title=‘myexample’
The second query would be
SELECT * FROM example WHERE title=‘myexample’ AND description=‘helloworld’
Please add some code what you’ve already tried and where you hit an roadblock, otherwise it’s pretty hard to help you here. You probably want to look for into_boxed
and BoxableExpression
in our API doc’s there are examples how to build dynamic filters.
My finished query looks like this:
running_event::dsl::event
.inner_join(
organizer::dsl::organizer.on(organizer::id.eq(event::fk_organizer_id)),
)
.inner_join(
event_category::dsl::event_category
.on(event_category::fk_event_id.eq(running_event::id)),
)
.inner_join(
event_discipline::table.on(event_discipline::fk_event_id.eq(running_event::id)),
)
.inner_join(category::table.on(category::id.eq(event_category::fk_category_id)))
.inner_join(discipline::table.on(discipline::id.eq(event_discipline::fk_discipline_id)))
.select((
event::title,
event::description,
event::target_date,
event::deadline,
event::address,
event::postcode,
event::city,
organizer::title,
organizer::email,
organizer::address,
organizer::postcode,
organizer::city,
organizer::phone,
organizer::website,
category::title,
discipline::distance,
discipline::fee,
discipline::starttime,
event_discipline::official,
));
Depending on the parameters in the query I have to filter for the following things:
.filter(event::target_date.ge(from_date).and(event::deadline.lt(to_date)))
.filter(event::postcode.eq(postcode))
.filter(discipline::distance.eq(distance))
.filter(category::title.eq(title))
But these filters have to be dynamic
Edit: Format
As mentioned above you want to look at the documentation of QueryDsl::into_boxed
.