php - 从 Laravel 中的集合结果中获取相关数据
问题描述
我通过公司的 id 检索了一组位置。一家公司可以有许多地点。现在我正在尝试从某个位置检索员工。一个位置可以有许多工作人员。
- 模型:
Firm
- hasMany 关系函数称为:firmLocations
。 - 模型:
Location
-belongsTo 关系函数调用Firm
。还有一个 hasMany 函数,称为Staff
. - 模型:
Staff
-belongsTo 关系函数调用Location
。
Staff
模型只与Location
模型有关。
代码位于控制器的显示功能中。
我想现在我有一家特定公司的相关地点,我可以使用该集合来获取员工。但是,我遇到了障碍,我们将不胜感激。谢谢。
public function showFirm($id)
{
// Get locations of a firm by id
$firm_locations = Firm::find($id)->firmLocations;
}
解决方案
您可以根据位置和公司检索员工。
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.
}
我假设你已经正确地建立了关系并且你已经掌握了关系的知识。
推荐阅读
- json - 用于数据负载的 Azure FCM NotificationHubClient 配置?
- mongodb - mongodb 从副本集实时迁移
- python - 优化或调整合并排序 3 方式的以下实现
- reactjs - 动态生成的材质 UI 单选按钮不可点击
- django - 在 Django 中设置函数字段的详细名称
- regex - Graylog 正则表达式在消息中提取第一个有效的 Mac 地址
- android - android渲染脚本函数
- python - 停止 rq worker 不会停止底层 ffmpeg 进程
- javascript - 使用 Chrome/Inspect Element 在我的 FTP 中查找文档时遇到问题
- javascript - 单击汉堡菜单后,我的导航菜单在桌面显示器上消失了吗?