Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 377
shoieb0101 Avatar asked Dec 09 '25 02:12

shoieb0101


1 Answers

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();
like image 95
Alexey Mezenin Avatar answered Dec 11 '25 17:12

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!