V
V
vetsinen2018-04-05 11:24:08
symfony
vetsinen, 2018-04-05 11:24:08

Is it possible to implement sorting by different fields in a table without code duplication?

Good afternoon, you need to implement on the backend sorting of records from the table by various fields that are taken using Doctrine QueryBuilder and issue to the rest api endpoint, is it possible to somehow parameterize the query to the database so that without duplicating the query for a selection in a dozen methods, get records sorted by one of the fields?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexalexes, 2018-04-05
@alexalexes

If you operate with the text of the request, then add a parameter to order by.

order by case 
            when :order_param = 1 then col_1
            when :order_param = 2 then col_2
           end,
           case 
            when :order_param = 1 then col_2
            when :order_param = 2 then col_1
           end

This means that if :order_param = 1 is given, then sorting will be equivalent to order by col_1, col_2.
If :order_param = 2 then order by col_2, col_1.
The case can also be embedded in subqueries if you have a complex query structure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question