列出 collection 中的子项目

Lists subitems in collection

我在 Laravel 5.1 中通过预加载获得了 collection。我知道有一种方法可以帮助我获取特定列的列表。但是我需要在我的超级 collection.

中获得最后的关系

下面的代码可以帮助我获取办公室的路线、路线客户和客户的积分。

$offices = Office::with( 'routes.customers.creditos' )->where( 'user_id', '=', $user->id )->get();

返回以下内容(数组格式):

array:1 [
  0 => array:10 [
    "id" => 10
    ...
    "routes" => array:2 [
      0 => array:10 [
        "id" => 1
        ...
        "customers" => array:2 [
          0 => array:21 [
            "id" => 1
            ...
            "creditos" => array:1 [
               "id" => 1
               ...
            ]
        ]
    ]
]

我只需要return学分:

$creditos = $offices->lists( 'routes.customers.creditos' )->all();

它不起作用,似乎 lists() 方法只是获取第一级中的列...

有(至少)2个选项:

  • 你像以前一样获取所有办公室数据,然后只提取信用 - 如果你只需要信用在你的行动中,你会获取很多不必要的数据和运行一些不必要的查询
  • 仅获取给定办公室的学分 - 这将提供更复杂的查询

选项 1:

$offices = Office::with( 'routes.customers.creditos' )->where( 'user_id', '=', $user->id )->get();
$creditos = array();
$offices->routes->map(function($route) use ($creditos) {
  $route->customers->map(function($customer) use ($creditos) {
    $creditos = array_merge($creditos, $customer->creditos->all());
  });
});

选项 2:

 $creditos = Credit::join('customers', 'creditos.customer_id', '=', 'customers.id')
  ->join('routes', 'customers.route_id', '=', 'routes.id')
  ->join('offices', 'routes.office_id', '=', 'offices.id')
  ->where('offices.user_id', '=', $user_id)
  ->get();