SummerSnow SummerSnow - 1 year ago 70
PHP Question

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

I have a many-to-many relationship in my app between

, 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


And this will get me two or more Employers


But I cannot simply


returns a

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download