Laravel5.5将列添加到第二个集合中

时间:2018-03-29 14:45:32

标签: laravel collections

我有一个关于admin的SQL请求:

$admin = Admin::findOrFail(Auth::guard('admin')->user()->id);

从这个sql请求我也设法获得管理员的用户...

$users = $admin->users;

每位用户必须遵循培训课程。我必须通过对每个用户使用SQL请求来计算它...所以我写了这个foreach语句

foreach ($users as $user) {
    $todo = User::select() .....where('users.id' = $user->id)->get();
    $done = User::select() .....where('users.id' = $user->id)->get();

    $totalTimes = $todo->toBase()->sum('dureeformation');
    $spendTimes = $done->toBase()->sum('dureeformation');
    $remainingTimes = $totalTimes - $spendTimes;

    $timeData[] = ['id' => $user->id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes, 'remainingTime' => $remainingTimes];
}

totalTimes,spendTimes和remainingTimes是对集合的操作,我得到预期的结果......

$users->each(function ($record) use ($timeData) {
    $record['totalTime'] = $timeData[$record['id']]['totalTime'];
    $record['spendTime'] = $timeData[$record['id']]['spendTime'];
    $record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
    //dd($record['totalTime']);


});

之后:

$timeData = collect($timeData);
$timeData= $timeData->keyBy('id');
$users = collect($users->toArray());

我有一个问题:

$users->each(function ($record) use ($timeData) {
    $record['totalTime'] = $timeData[$record['id']]['totalTime'];
    $record['spendTime'] = $timeData[$record['id']]['spendTime'];
    $record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
    //var_dump($record);
});

函数中的$ record给出了我所期望的... var_dump($ records)添加了预期的列,但我无法将这些结果从函数中删除。

我试着这样做:

$variable = $users->each(function ($record) use ($timeData)... 
dd($variable) 

但未成功......

1 个答案:

答案 0 :(得分:0)

在我看来,$timeData数组的构建方式与访问它的方式不同。在您正在执行的代码中

$timeData[] = [
    'id' => $user->id,
    'totalTime' => $totalTimes,
    'spendTime' => $spendTimes,
    'remainingTime' => $remainingTimes,
];

将产生这样的数组

[
    0 => [
        'id' => 17,
        'totalTime' => 5,
        'spendTime' => 4,
        'remainingTime' => 3
    ],
    1 => [
        'id' => 17,
        'totalTime' => 7,
        'spendTime' => 5,
        'remainingTime' => 2
    ]
]

但你真正想要的是将id作为索引,对吗?然后你必须以这种方式构建数组:

$timeData[$user->id] = [
    'totalTime' => $totalTimes,
    'spendTime' => $spendTimes,
    'remainingTime' => $remainingTimes,
];

或者,作为替代方案,执行不同的查找:

$users->each(function ($record) use ($timeData) {
    $times = array_first($timeData, function ($value, $key) use ($record) {
        return $value['id'] === $record['id'];
    });
    $record['totalTime'] = $times['totalTime'];
    $record['spendTime'] = $times['spendTime'];
    $record['remainingTime'] = $times['remainingTime'];
});

但这两种解决方案都有利有弊。一方面,使用用户标识符作为索引将产生一个仅部分填充的巨大数组。另一方面,第二种解决方案有点慢。只要您不打算处理$timeData数组中的数千个条目,这不会成为问题。