ihaveaname
ihaveaname

Reputation: 138

Selecting from more than one model in an eloquent many to many relationship

I have a many-to-many relationship in my app between Employers and Employees, and I am trying to determine how to query for all "Employees" who work for a set of companies.

For example I may wish to select all the employees of "Industry Corp" and "Shovels Unlimited"

Example Data Relation

If I query for these individually I will get [Sam, Nathan] for Industry Corp, and [Kory, Nathan] for Shovels Unlimited

I could select these individually, and then combine, but then I get a duplicate Nathan.
[Sam, Nathan, Kory, Nathan]

Is there a way to make this query to return the result [Sam, Nathan, Kory] ?


I have tried a bunch of things, but nothing I attempt is getting exactly what I need.

This will get me what I need from one employer

Employer::find(2)->employees()->get()

And this will get me two or more Employers

Employer::::findMany([2,4]);

But I cannot simply

Employer::::findMany([2,4])->employees()->get();

because findMany([...]) returns a Illuminate\Support\Collection

Upvotes: 1

Views: 46

Answers (1)

user1669496
user1669496

Reputation: 33078

Yeah, you want to use whereHas.

$employer_ids = [1, 2, 3];  // These are ids of employers you want to get all employees for.
$employees = Employee::whereHas('employers', function($q) use ($employer_ids) {
    $q->whereIn('employer_id', $employer_ids);
});

Upvotes: 2

Related Questions