I am using "orWhere" clause in my Laravel application where I build the datatable query. The results I get are perfect, but when I try to use the search it is messing up the results, no errors occur, but the results are not accurate at all.
This is my query:
$data = Result::where(function($query) {
$query->where('type', 'news');
})
->orWhere(function($query) {
$query->where('type', 'editorials')
->where('year', '>=', 2018);
})
->select('results.*');
If I remove the orWhere clause, the search is fixed. The problem is not from the callback function it is from the orWhere. I am not sure how to fix this. Any suggestions will be appreciated.
I think the prob is on your query. Maybe try to chain orWhere inside one closure instead.
$data = Result::where(function($query) {
$query->where('type', 'news')
->orWhere(function($query) {
$query->where('type', 'editorials')
->where('year', '>=', 2018);
})
->select('results.*');
Even if I make the query like this:
$data = Result::where('type', 'news')->orWhere('type', 'editorials')->select('results.*');
The search problem remains (the above query is just to test it). The orWhere clause causes the problem I think. The thing is I need orWhere clause so I can exclude all the editorials before 2018, so I have to use it.
I followed your suggestion. With a query such as this:
$data = Result::where(function($query) {
$query->where('type', 'news');
$query->orWhere(function($query_two) {
$query_two->where('type', 'editorials')
->where('year', '>=', 2018);
});
})
->select('results.*');
So indeed the problem comes if orWhere is in the query. But if orWhere is in the callback, the problem disappears.
Thank you for the suggestion. Hope this also helps to someone else! :)
This helped me too, thank you.