Problem with orWhere method in Builder Class
Hello, I have a huge filter that can recognize a lot of things in connection with a keyword. First, we had the Filter only search for the keyword in the title and anything that comes in addition to said filter works perfectly well, now someone recognized it and wanted to recognize the body as well.
So before I had the statement like that, in the statement is also the previously changed code. With the Statements which are kinda essential.
$eventsList = Post::select('posts.*')->where('posts.type', self::EVENT_POST_TYPE);
if ($q) {
$eventsList = $eventsList->where('posts.title', 'LIKE', '%' . $q . '%');
//changed to
//$eventsList = $eventsList->where('posts.title', 'LIKE', '%' . $q . '%')->orWhere('posts.body', 'LIKE', '%' . $q . '%');
}
...a lot of other statements
//Main Statements where the misstake comes in to play
if ($fromDate) {
$eventsList = $eventsList->whereHas('meta', static function ($q) use ($fromDate) {
$q->where('key', 'datumsbereich_value');
$q->where('value', '>=', $fromDate);
});
}
if ($toDate) {
$eventsList = $eventsList->whereHas('meta', static function ($q) use ($toDate) {
$q->where('key', 'datumsbereich_value2');
$q->where('value', '<=', $toDate);
});
}
Later I used the pagination method to get a nice small collection.
The Problem is if I put it with the orWhere Method in the beginning some Post will completely ignore the date statements.
I have a kind of a workaround for it already which is okay for the people who found the error. But I try to find some method to search for both and then the other filter statements will work perfectly well.
My Workaround:
$eventsList = Post::select('posts.*')->where('posts.type', self::EVENT_POST_TYPE);
if ($q) {
$eventsList = $eventsList->where('posts.title', 'LIKE', '%' . $q . '%');
if ($eventsList->count() === 0) {
$eventsList = Post::select('posts.*')->where('posts.type', self::EVENT_POST_TYPE);
$eventsList = $eventsList->where('posts.body', 'LIKE', '%' . $q . '%');
}
}
I simply check if there is no title match then it should watch also on the body if it will find something. Sure as soon as it finds a title it will not look over the body for now that is fine but maybe in the future would be great if it finds both the title and body and uses the other filters fine.
If somebody of you knows where the problem is coming from I would appreciate your help. :)
Best Regards
Please or to participate in this conversation.