从 eloquent 多对多关系中的多个模型中选择

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

我的应用程序中 EmployersEmployees 之间存在多对多关系,我正在尝试确定如何查询所有 "Employees" 工作的人一组公司。

例如我可能希望 select "Industry Corp" 和 "Shovels Unlimited"

的所有员工

如果我单独查询这些,我将得到 Industry Corp 的 [SamNathan] 和 [ KoryNathan] for Shovels Unlimited

我可以 select 这些单独的,然后合并,但我得到了一个重复的 Nathan。
[Sam, Nathan, Kory, Nathan]

有没有办法使这个查询 return 结果 [Sam, Nathan, 科里] ?


我已经尝试了很多东西,但我尝试的一切都没有得到我需要的东西。

这将使我从一个雇主那里得到我需要的东西

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

这将使我获得两个或更多的雇主

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

但我不能简单

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

因为findMany([...])return是Illuminate\Support\Collection

是的,您想使用 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);
});