简体   繁体   English

如何获取多个 Jsonb 值的总和 Laravel

[英]How To Get Sum On Multiple Jsonb Values Laravel

I am running a cron each Weak and saving customers' data on a new table, For a customer per month 4 records, End of every month I am running a new cron and need to get the sum on customer data and save it on a new table to send some reports.我每个 Weak 都运行一个 cron,并将客户的数据保存在一个新表上,对于一个客户,每月 4 条记录,每个月底我都在运行一个新的 cron,需要获取客户数据的总和并将其保存在一个新表上表发送一些报告。

weak data is saved like this弱数据是这样保存的

[customer_id = 25
data {
  "body": {
    "aaa": 0,
    "bbb": 98,
    "ccc": 0,
    "ddd": 1,
  }
}
],
[customer_id = 25
data {
  "body": {
    "aaa": 22,
    "bbb": 22,
    "ccc": 22,
    "ddd": 12,
  }
}
]

since it is a JSON b column I couldn't get the sum因为它是 JSON b 列,所以我无法得到总和

This is my code这是我的代码

 $summaryReport = summaryreport::all();
                   
 foreach($summaryReport as $report){
          
     $data['aaa'][$report->customer_id] = (json_decode($report->data)->body->aaa);
    }
     Model::insert($data);
    ``

Firstly filter your reports by using the collection method where() , to only include the correct users.首先使用收集方法where()过滤您的报告,以仅包含正确的用户。 From there you can sum on the collection summing all the data entries, but do it with the closure approach.从那里您可以对所有数据条目求和的集合求和,但是使用closure方法来完成。 Where you can fetch the data from the data structure, to call another sum() .您可以从数据结构中获取数据的位置,以调用另一个sum()

$reportData = collect(json_decode($report))->where('customer_id', $report->customer_id);

$reportData->sum(function ($item) {
    return collect($item->data->body)->sum();
});

This is simply an exercise in knowing and understanding collections methods and how to utilize them in a non standard data structure.这只是了解和理解 collections 方法以及如何在非标准数据结构中使用它们的练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM