首页 > 解决方案 > Laravel Pluck 3 数组

问题描述

我可以拔出像这样的 3 个数组,因为只显示了两个吗?

$data = Receipt::select(DB::raw("DATE(created_on) as date"), DB::raw("sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt"), DB::raw("sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
    ->groupBy('date')
    ->pluck('cnt_receipt', 'cnt_invoice', 'date')->all();

如果没有,我怎样才能显示这 3 个数组?

我想要这样的输出

date                 cnt_receipt       cnt_invoice
2021-01-01             5                6
2021-01-02             8                5
2021-01-03            10                9
2021-01-04            11                9

我需要将这些数据作为数组获取,因为图表 js 代码需要 array_keys 和 array_values

$chart= new Chart;
$chart->labels = (array_keys($data));
$chart->r_dataset = (array_values($data));
$chart->i_dataset = (array_values($data));

图表类

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Chart extends Model
{
    //
}

标签: laravellaravel-7

解决方案


你需要使用的是reduce这里,有点笨拙的方式,但它会起作用。

$data = Receipt::select(DB::raw("DATE(created_on) as date, sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt, sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
   ->groupBy('date')->all();

然后;

$chartInitial = new Chart();
$chartInitial->labels = [];
$chartInitial->r_dataset = [];
$chartInitial->i_dataset = [];

$chart = $data->reduce(function($obj, $row){
    $obj->labels[] = $row->date;
    $obj->r_dataset[] = $row->cnt_receipt;
    $obj->i_dataset[] = $row->cnt_invoice;
    return $obj;
}, $chartInitial);

它将所有行数据推送到该 Chart 对象中各自的数组中。


推荐阅读