首页 > 解决方案 > 从 Laravel 中的集合结果中获取相关数据

问题描述

我通过公司的 id 检索了一组位置。一家公司可以有许多地点。现在我正在尝试从某个位置检索员工。一个位置可以有许多工作人员。

Staff模型只与Location模型有关。

代码位于控制器的显示功能中。

我想现在我有一家特定公司的相关地点,我可以使用该集合来获取员工。但是,我遇到了障碍,我们将不胜感激。谢谢。

public function showFirm($id)
{
    // Get locations of a firm by id
    $firm_locations = Firm::find($id)->firmLocations;
}

标签: phplaraveleloquent

解决方案


您可以根据位置和公司检索员工。

public function showFirm($id) {

    // Get locations of a firm by id with staff member from location

    $firm_locations = Firm::where('id',$id)->with('firmLocations.staff')->first();

    // Above function retrieve Firm with Location and Location will have staff.
}

我假设你已经正确地建立了关系并且你已经掌握了关系的知识。


推荐阅读