Reputation: 988
I have a number of search terms I want to use in an SQL query using Laravel 5.1. This is my code
foreach ($searchTerms as $term) {
$query->where(function($query) use ($query, $term){
$query->where("profiles.text", "LIKE", "%{$term}%")
->orWhere("protocols.text", "LIKE", "%{$term}%");
});
}
This is the SQL I get from it:
where 'profiles'.'text' LIKE ? or 'protocols'.'text' LIKE ? and
'profiles'.'text' LIKE ? or 'protocols'.'text' LIKE ?
And this is the SQL I need:
where ('profiles'.'text' LIKE ? or 'protocols'.'text' LIKE ?) and
('profiles'.'text' LIKE ? or 'protocols'.'text' LIKE ?)
What can I do to get the correct query string?
Thanks
Pida
Upvotes: 2
Views: 2489
Reputation: 404
The problem is, that in your closure you are "using" the $query. The $query is passed as an argument and you shouldn't declare it again in the use() block.
The correct code is:
foreach ($searchTerms as $term) {
$query->where(function($query) use ($term){
$query->where("profiles.text", "LIKE", "%{$term}%")
->orWhere("protocols.text", "LIKE", "%{$term}%");
});
}
Upvotes: 3
Reputation: 5443
try this
$query->where(function($query) use ($query, $term){
$query->where("profiles.text", "LIKE", "%{$term}%")
->orWhere("protocols.text", "LIKE", "%{$term}%");
});
$query->where(function($query) use ($query, $term){
$query->where("profiles.text", "LIKE", "%{$term}%")
->orWhere("protocols.text", "LIKE", "%{$term}%");
});
Upvotes: 0