Reputation: 417
I have a model that has a field type
which consists of several words. The string looks like this: modern premium hot
.
How to get relevant results if I want to filter it with an array like this one:
$filter = [0 => 'modern', 1 => 'hot'];
$search = implode(' ', $filter);
$results = Model::where('type', $search)->get();
The above example will not return anything because it will try to match modern premium hot
with modern hot
and its not the same, but how to get all relevant results that contain the words modern
and hot
at the same time in the type
fields?
In other words how to get all results that have all elements of the array in the type
field, which is a string?
Upvotes: 0
Views: 696
Reputation: 17206
You use orWhere()
$filter = [0 => 'modern', 1 => 'hot'];
$query= Model::query();
foreach($filter as $term) {
$query->orWhere('type', $term);
}
$results = $query->get();
if you have other where()
in your query, use this
$filter = [0 => 'modern', 1 => 'hot'];
$results = Model::where(function($query) use($filter) {
foreach($filter as $term) {
$query->orWhere('type', $term);
}
})
//->where(....)
->get();
Upvotes: 1
Reputation: 1230
Maybe you need a fulltext service like Elastic Search or Algolia, or even look at fulltext search on your database engine (assuming MySQL, check this link).
But if you really need to move on as it is going, you may try something like that:
$query = Model::query();
foreach ($filter as $term) {
$query->orWhere('type', 'LIKE', "%{$term}%");
}
$results = $query->get();
Upvotes: 1