列出集合中的子项目

布赖恩

我有一个渴望加载Laravel 5.1的集合。我知道有一种方法可以帮助我获取特定列的列表。但是我需要获得超级收藏中的最后一个恋爱关系。

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

$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
               ...
            ]
        ]
    ]
]

我只需要返还学分:

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

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

jedrzej.kurylo

至少有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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章