使用laravel将值合并到一个集合中

时间:2018-01-18 13:29:08

标签: php laravel

我有一张桌子只能在每个qid上提交最多两次。

首先提交='提交'在状态栏上。

第二次提交='重新提交'在状态栏上。

id username qid amount    status 
1    john    2    150    submitted
2    john    2    120    resubmitted
3    david   2    100    submitted
4    david   2     80    resubmitted

我想在下面的集合中添加第一笔金额,这样我就可以在视图中显示两个金额。

    "id" => 1
    "username" => john
    "amount" => "120.00"
 **"first_amount" => "150.00"**
    "status" => "resubmitted"

刀片:

@foreach($xxx as $x)

{{$x->amount}}
{{$x->first_amount}}

@endforeach

这可能吗?

3 个答案:

答案 0 :(得分:0)

添加" first_amount"表的列,默认值为0.然后,当您检索它时,它将填充到集合中。您可以设置" first_amount"的值。当你插入"重新提交"行。

它还可以帮助您修改集合以向其中添加值。

答案 1 :(得分:0)

您可以加载一次数据:

$collection = Model::get();

然后使用该集合而不执行任何其他查询:

@foreach($collection->where('status', 'resubmitted') as $x)
    {{ $x->amount }}
    {{ $collection->where('status', 'submitted')->firstWhere('qid', $x->qid)->amount }}
@endforeach

或者您可以重建集合以向其添加first_amount

$collection = $a->where('status', 'resubmitted')->map(function($i) use($collection) {
    $i['first_amount'] = $collection->where('status', 'submitted')->firstWhere('qid', $i['qid'])->amount;
    return $i;
});

答案 2 :(得分:0)

您可以在查询中执行此操作或转换结果(通过集合)。

一种可能的解决方案(通过Collection)是:

$collection = (new Collection($data))->groupBy('username')->map(function($userItems, $username) {
  $firstAmount = $userItems->where('status', 'submitted')->first();

  return $userItems->map(function($data) use ($firstAmount) {
    return array_replace_recursive($data, ['first_amount' => $firstAmount['amount']]);
  });
})->flatten(1);

这会将第一笔金额添加到所有结果中。

另一种方式就像Alexey发布的那样。基本上,您获取“重新提交”值并将first_amount添加到其中。但是,这只会添加到“重新提交”的值中(带有“已提交”的项目不会包含first_amount键)。