I want to remove where clauses in some conditions:
$q = Thread::with('comments')->take(10);
if(strlen($input) < 4){
$result = $q->where('title', '~', "^$input$")->get();
if($result->isNotEmpty()){
return $result;
}
// if was empty:
}
// How to clean the where clause from the above here? because it affect the query below:
$result = $q->where('title', 'like', "%$input%")->get();
The problem is the first where clause affects the second one if the data was empty, How can i remove existing where clauses when needed ? also the newQuery()
is not working in my case.
Note that i'm using two seperate statement in postgres ~
and 'like'
Something like reorder() for where clauses
CodePudding user response:
Use Conditional Clauses
$threads = Thread::with('comments')->when(strlen($input) < 4, function ($query) use ($input) {
return $query->where('title', '~', "^$input$");
}, function ($query) use ($input) {
return $query->where('title', 'like', "%$input%");
})->take(10)->get();
https://laravel.com/docs/8.x/queries#conditional-clauses
If you want to give it a second change I would write that logic like this. Comments are loaded only if they are needed.
if (strlen($input) < 4) {
$threads = Thread::where('title', '~', "^$input$")->take(10)->get();
if ($threads->isNotEmpty()) {
return $threads->load('comments');
}
}
return Thread::with('comments')->where('title', 'like', "%$input%")->take(10)->get();
CodePudding user response:
Yes there is a way to do it
$q = Thread::with('comments')->take(10);
if(strlen($input) < 4){
$result = $q->where('title', '~', "^$input$")->get();
if($result->isNotEmpty()){
return $results;
}
}
// getQuery() is a query builder method that contains all the groupings, selects, orders, wheres, joins etc for the query that you are accessing or trying to build.
$q->getQuery()->wheres= [];
$result = $q->where('title', 'like', "%$input%")->get();
CodePudding user response:
if you cloning before add where it works the same as deleting where
...
if(strlen($input) < 4){
$result = (clone $q)->where('title', '~', "^$input$")->get();
if($result->isNotEmpty()){
return $results;
}
}
$result = $q->where('title', 'like', "%$input%")->get();
...