'How to use regex or any other operator with whereIn clause
Is there any way we can use operator or regex as we normally do with the whereIn() clause.
I want to use something like this
$query->whereIN(name,'like','%test%');
I'm getting multiple data in an array. It should return data if name contains any of the keywords.
For eg. $searchArray = ['test','case']; So it should return data with name containing values in $searchArray
Is it possible?
Solution 1:[1]
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
https://laravel.com/docs/9.x/queries#additional-where-clauses
Try this:
where('title', 'like', '%' . $keyword . '%')
UPDATE:
$query->where(function ($query) use ($keyword, $columns) {
foreach ($columns as $key => $column) {
$clause = $key == 0 ? 'where' : 'orWhere';
$query->$clause($column, "LIKE", "%$keyword%");
if (!empty($relativeTables)) {
$this->filterByRelationship($query, $keyword,
$relativeTables);
}
}
});
Solution 2:[2]
I Had the same problem. The only way i was able do solve, was with mongodb native query aggregation. Let me show how i did.
I made a function to use in all of my system
public function matchLikeIn($match, $field, $value,$option = 'i')
{
try {
$or = array();
foreach($value as $v){
$or['$or'][] = [
$field => [
'$regex' => $v,
'$options' => $option
]
];
}
$match['$and'][] = $or;
return $match;
} catch (Exception $e) {
}
}
A exemple using it
$match = array();
$names = ["name1","name2"];
$match = $this->matchLikeIn($match, "name", $names, 'i');
$aggregate[] = ['$match' => $match];
$query = Model::raw(function ($collection) use ($aggregate) {
return $collection->aggregate($aggregate);
})->toArray();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |