I have 3 tables:
Certificates - all available certificates
Users - table of users
UserCertificates - certificates that users own. each record has it's own ID, user_id and certificate_id foreign keys.
Now, I have an array (or just one value) of the certificates IDs, and I need to get all users who own those chosen certificates. So if the certificate IDs are 1,4,7 I need to select all users who own ALL of those certificates, not 1 OR 4 OR 7.
I have the working code, it took me few good hours to get it working but it does not look clean. Is there a cleaner way of doing it?
$requiredCertificates
is an array of certificate_id's
public function getMatches(Opportunity $opportunity)
{
$requiredCertificates = $this->getRequiredCertificates($opportunity);
return User::with('certificates')
->whereHas('certificates', function ($query) use ($requiredCertificates) {
$query->select(\DB::raw('count(distinct certificate_id)'))->whereIn('certificate_id', $requiredCertificates);
}, '=', count($requiredCertificates))
->get();
}