shoieb0101 shoieb0101 - 27 days ago 10
PHP Question

Match array of ids from pivot table

Scenario

I have 3 main tables

Employees
,
Jobs
,
Skills
.
Employees
and
Jobs
has
many-to-many
relationship with
Skills
table.

So, an employee can have skills
1,2,3,5
. A
job
may requires
skills
1,3,5
.

Now my question is how can I match the id's in an eloquent query. Like, if I want to search all the
employees
for a
job
requiring
skills 1,3,5
, it should search all the
employees
having all those
skills(1,3,5)

Answer

You said you have an array of IDs, so use multiple whereHas():

$employees = Employee::JobLocations($jobZipId);

foreach ($skillIds as $id) {
    $skilledEmployees = $emloyees->whereHas('skills', function ($q) use ($id) {     
        $q->where('id', $id);
    });
}

$skilledEmployees = $skilledEmployees->get();
Comments