I am trying to pull users based on their tags where ALL keywords match.
Take this working code:
$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');
$search_results = User::where('user_type_id', 1)
->where('approved', 1)
->whereHas('tags', function ($q) use($search_terms) {
$q->whereIn('name', $search_terms);
})->get();
At the minute I am using whereIn() to do this, but it will pull users even if they have 1 match out of all the inputted keywords. So if we have keyword 1, keyword 2, keyword 3, keyword 4. The query should only pull results where ALL the keywords are matched in the tags table for a given user.
CodePudding user response:
I think this will work, could you please check
$search_terms = array('keyword 1', 'keyword 2', 'keyword 3', 'keyword 4');
$search_results = User::where('user_type_id', 1)
->where('approved', 1)
->whereHas("tags", function($q) use ($search_terms) {
$q->whereIn("name", $search_terms);
}, "=", count($search_terms));
->get();
