B
B
BonBon Slick2017-06-15 20:39:12
PostgreSQL
BonBon Slick, 2017-06-15 20:39:12

Apply filters to SQL query if any?

PostgreSQL 9.6
Filters, there may be more:

$regionFilter = $request->get('filter_1') ? $request->get('filter_1') : "";
$nameFilter = $request->get('filter_2') ?$request->get('filter_2')  : "";
$roleFilter= $request->get('filter_3') ? $request->get('filter_3') : "";


Query with subqueries:

$wonRollGame = Game::select('posts.*' ....)
                ->join('users', function ($join) use ($nameFilter , $roleFilter) {
                    $join->on('posts.user_id', '=', 'users.id')
                        ->where('users.name', 'LIKE', '%' . $nameFilter . '%')
                        ->where('users.role', '=', $roleFilter);
                })
                ->join('region', function ($join) use ($regionFilter ) {
                    $join->on('posts.restriction_id', '=', 'region.id')
                        ->where('region.id', '=', $regionFilter);
                })
                ->first();

If all filters are filled, the request works well, but if at least one empty ""
The fact is that the filter contains, for example, id, it cannot be set specifically to any one. He either is, or he is not. For example, as above, there are regional restrictions, there is an id, the filter must be applied if the user has selected a region. Otherwise, take all regions, I tried to leave the field empty by putting "", then it gives an error. By default, it is also impossible to put, what to do?
And this kind of code creates chaos, a lot of duplicates and if statements
if ($published == true)
    $query->where('published', '=', 1);

Yes, and you can not enter if in the subquery.
Mistake:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type double precision: ""

Perhaps there is some default value, or a function that makes a selection by default, without a filter, TRIM (). I saw such a solution, mine is a crutch: WHERE title IS NULL OR LEN(Title) > 0
Please tell me, so how can I use filters, if any, without duplicates of the request code c if else?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
UksusoFF, 2017-06-15
@BonBonSlick

https://github.com/Tucker-Eric/EloquentFilter

B
Boris Korobkov, 2017-06-16
@BorisKorobkov

if ($published == true) {
    $query->where('published', '=', 1);
}

- this is a completely normal option.
Is it possible to shorten it a bit:
$published && $query->where('published', '=', 1);

D
d-stream, 2017-06-15
@d-stream

I saw such a solution, mine is a crutch: WHERE title IS NULL OR LEN (Title) > 0

In fact, such a class of solutions from the point of view of SQL are quite working and rather not crutch, but with pseudo-hints

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question