简体   繁体   English

从 Laravel 中的集合结果中获取相关数据

[英]Getting related data from a collection result in Laravel

I retrieved a collection of locations by id of a Firm.我通过公司的 id 检索了一系列位置。 One firm can have many locations.一家公司可以有多个地点。 Now I'm trying to retrieve staff from a location.现在我正在尝试从某个位置检索员工。 One location can have many staff members.一个地点可以有许多工作人员。

  • Model: Firm - hasMany relationship function called: firmLocations .模型: Firm - hasMany 关系函数调用: firmLocations
  • Model: Location - belongsTo relationship function called Firm .模型: Location -belongsTo 关系函数称为Firm Also had a hasMany function called Staff .还有一个名为Staff的 hasMany 函数。
  • Model: Staff - belongsTo relationship function called Location .模型: Staff -belongsTo 关系函数称为Location

Staff model only relates with Location model. Staff模型仅与Location模型相关。

Code is in a show function in a controller.代码位于控制器中的显示功能中。

I thought now that I have related locations for a particular firm I can just use that collection to get staff members.我想现在我有特定公司的相关位置,我可以使用该集合来获取员工。 However, I've hit a roadblock and help would be greatly appreciated.但是,我遇到了障碍,将不胜感激。 Thanks.谢谢。

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

You can retrieve Staff based on location along with firm.您可以根据位置和公司检索员工。

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.
}

I am assuming you've set up relationship correctly and you've working knowledge of relationship.我假设您已经正确地建立了关系,并且您已经掌握了关系的工作知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM