MedicOneSystems / livewire-datatables

Advanced datatables using Laravel, Livewire, Tailwind CSS and Alpine JS
https://livewire-datatables.com/
MIT License
1.19k stars 258 forks source link

searchable() filterable() dosent work propertly when query have where() and orWhere() in the same query() #456

Closed insulae closed 2 years ago

insulae commented 2 years ago

I have a query like this:

$query = Petition::query()
            ->Where('effector_id','1')
            ->orWhere('state','2');

The query is simple it brings some records that belong to the effector selected in the first where() or those records that were released and do not have an effector ( the query is more complicated, but I have summarized it to show what happens)

Working OK, WITHOUT ->orWhere('state','2'); :

If I remove the ->orWhere('state','2'); I can use the filterable() or the searchable() correctly.

(A = APROBADA, B = BLOQUEADA) image

(search for a partial name) image

Working WRONG WITH the second where ->orWhere('state','2'); :

(same examples)

image

image

I dont know if this it's my error (I am new in Laravel, livewire-datatables and Query Builder) or a limitation of livewire-datatables.

I think the problem is that when I use searchable() or fitrable() it applies on the first where() and then the orWhere() records are added:

(TABLE ->where) ->applyFilter + (TABLE ->orWhere)

when it should be:

(TABLE->where + TABLE->orWhere) -> applyFilter

insulae commented 2 years ago

Ok I resolved the problem (I need to read more about Query Builder). I leave my solution in case anyone has the same problem.

In normal SQL Query you can do this:

SELECT * 
FROM petitions
WHERE efector_id = 1
OR state = 2

then I thought that if the problem was that the filtering got in the middle of my query do something like this:

SELECT * 
FROM petitions
(
 WHERE efector_id = 1
 OR state = 2
)

both query's made the same result but the second has group search. To do this with Query Builder you can do it like this:

$query = Petition::query()
->where(function ($query) {
  $query->where('efector_id', '1')
  ->orWhere('state','2');
})
return $query;