I am trying to get search results where atleast 2 or 3 keywords match in keywords array.
Example Table
Name | Categories | Keywords |
---|---|---|
name1 | category1,category2,category3 | keyword1,keyword4,keyword3,keyword2 |
name2 | category4,category2,category6 | keyword6,keyword4,keyword3 |
name3 | category5,category2,category1 | keyword2,keyword5,keyword3 |
name4 | category7,category3,category4 | keyword1,keyword4,keyword8,keyword6 |
$categories = explode(',' ,$site->category);
$keywords = explode(',' ,$site->keywords);
foreach( $categories as $category)
{
$results = Website::where('category', 'like',"%{$category}%")
->where('name', '!=', $name)
->where(function ($query) use ($keywords){
foreach( $keywords as $keyword)
{
$query->orWhere('keywords','like', "%{$keyword}%");
}
}
)
Above codes returns all results that match single keyword, **Requirement **: Only results that match more than 2 keywords. How can I achieve this?
CodePudding user response:
Try to use where-subquery. Something like this:
Website::where('category', 'like',"%{$category}%")
->where('name', '!=', $name)
->where(function ($query) {
$query->selectRaw('count(websites.keywords)')
->from('websites')
->where('keywords', 'like', "%{$keyword}%")
}, '>', 2)
->get();