【问题标题】:Laravel Pluck 3 arraysLaravel Pluck 3 数组
【发布时间】:2021-01-07 07:04:44
【问题描述】:

我可以像这样提取 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
{
    //
}

【问题讨论】:

  • 你想得到这 3 个值 'cnt_receipt', 'cnt_invoice', 'date' 吗?
  • 删除这一行再试一次->all()
  • 我尝试删除该行-&gt;all(),它有错误array_keys() expects parameter 1 to be array, object given
  • 使用->toArray()
  • 它也返回与 all() 相同的结果。我将编辑我的问题以显示应该是什么输出。

标签: laravel laravel-7


【解决方案1】:

你需要在这里使用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);

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

【讨论】:

  • Indirect modification of overloaded property App\Chart::$labels has no effect 在代码$obj-&gt;labels[]
  • 你能分享你App\Charts模型的代码吗?
  • 我没有在App\Chart模型中放任何代码
  • 你能分享Chart类吗?
猜你喜欢
  • 2016-03-28
  • 2018-05-10
  • 2021-12-01
  • 1970-01-01
  • 2017-03-07
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多