【问题标题】:merge values into one collection using laravel使用 laravel 将值合并到一个集合中
【发布时间】:2018-01-18 13:29:07
【问题描述】:

我有一个表格,每个 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

这可能吗?

【问题讨论】:

  • 不是一个明确的问题,结果是什么
  • 表格数据与描述不符。我看到相同 qid 的 4 个条目。
  • 重新提交的值可以超过一个吗?

标签: php laravel


【解决方案1】:

您可以加载一次数据:

$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;
});

【讨论】:

  • 感谢您的回复。当我尝试您的第一个代码时出现此错误。调用未定义的方法 Illuminate\Database\Query\Builder::firstWhere()。我会尝试第二个。
  • @wwwrrrxxx 请尝试更新代码,同时请说明您是如何加载数据的。
【解决方案2】:

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

它还可以让您不必修改集合以向其中添加值。

【讨论】:

  • 感谢您的回复。如果其他方式不起作用,我会考虑你的。
【解决方案3】:

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

一种可能的解决方案(通过 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 键)。

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2011-10-28
    • 2017-07-18
    • 1970-01-01
    • 2019-10-07
    • 2020-01-25
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多