Laravel集合-only()到主数组和子数组

时间:2018-07-07 14:39:33

标签: arrays laravel recursion collections

我有集合(从具有复杂查询的数据库中),并且我试图通过-> only()方法仅获取其中的几个值,但它不起作用。

收藏:

0 => array:4 [
  "id" => 1
  "start_date" => "2018-07-07 14:00:00"
  "end_date" => "2018-07-07 15:00:00"
  "child" => array:5 [
    "id" => 1
    "name" => "Mr. Davin Conroy Sr."
    "email" => "prempel@example.com"
    "created_at" => "2018-07-06 22:28:16"
    "updated_at" => "2018-07-06 22:28:16"
  ]
]
1 => array:4 [
  "id" => 2
  "start_date" => "2018-07-07 15:00:00"
  "end_date" => "2018-07-07 16:00:00"
  "child" => array:5 [
    "id" => 1
    "name" => "Mr. Davin Conroy Sr."
    "email" => "prempel@example.com"
    "created_at" => "2018-07-06 22:28:16"
    "updated_at" => "2018-07-06 22:28:16"
  ]

我的代码:

    $subset = $monitorList->map(function ($monitor) {
        return collect($monitor->toArray())
            ->only(['id', 'start_date', 'end_date', 'child.name', 'child.email'])
            ->all();
    });

但是它丢失了child.name。该问题的解决方案是什么?

0 => array:3 [
  "id" => 1
  "start_date" => "2018-07-07 14:00:00"
  "end_date" => "2018-07-07 15:00:00"
]
1 => array:3 [
  "id" => 2
  "start_date" => "2018-07-07 15:00:00"
  "end_date" => "2018-07-07 16:00:00"
]

2 个答案:

答案 0 :(得分:1)

似乎唯一的方法无法获取嵌套参数,因此您应该使用自己的转换,如:

$subset = $monitorList->map(function ($monitor) {
    $value = collect($monitor->toArray())->only('id', 'start_date', 'end_date')->all();
    $value['child'] = collect($monitor->child->toArray())->only('name', email')->all();      
    return $value;
});

答案 1 :(得分:1)

您可以使用

$subset = $monitorList->map(function ($monitor) {
     $data = $monitor->only('id', 'start_date', 'end_date');
     $data['child'] = $monitor->child->only('name', 'email');
     return $data;
});

在这种情况下,最好的做法是仅获取需要的数据。

$monitorList = Motor::with('child:id,name,email')
    ->get(['id', 'id_user', 'start_date', 'start_date']);

您也可以在自己的情况下使用此代码

$subset = $monitorList->map(function ($monitor) {
     $monitor->child->makeHidden('updated_at', 'created_at', 'id');
     return $monitor;
});

为了良好作法,您可以使用

$monitorList = Motor::with('child:id,name,email')
    ->get(['id', 'id_user', 'start_date', 'start_date']);

$subset = $monitorList->map(function ($monitor) {
     $monitor->child->makeHidden('id');
     return $monitor;
});