叶片模板中Eloquent集合上的碳过滤器产生了奇怪的结果


Strange results with Carbon filter on Eloquent collection in blade template

我有一个奇怪的问题,我看不到任何明显的解决方案。

我正在构建过去30天的事务总数的jQuery图,但我没有得到正确的输出。以下是相关刀片模板代码:

@for ($i = 29; $i >= 1; $i--)
{y: '{{ 'Carbon'Carbon::now()->subDays($i)->toDateString() }}', item1: '{{ $transactions->whereDate('created_at', '=', 'Carbon'Carbon::now()->subDays($i)->toDateString())->where('status', 'C')->sum('amount') }}'},  
@endfor
{y: '{{ 'Carbon'Carbon::now()->toDateString() }}', item1: '{{ $transactions->where('created_at', '>=', 'Carbon'Carbon::now()->toDateString())->where('status', 'C')->sum('amount') }}'}

对于我的伪数据,当$i=3时,它应该返回"10.00",其他所有数据都应该返回"0"。

注意:如果我将FIRST输出设为"3天前",它将返回预期值。示例:

{y: '{{ 'Carbon'Carbon::now()->subDays(3)->toDateString() }}', item1: '{{ $transactions->whereDate('created_at', '=', 'Carbon'Carbon::now()->subDays(3)->toDateString())->where('status', 'C')->sum('amount') }}'},
@for ($i = 29; $i >= 1; $i--)
{y: '{{ 'Carbon'Carbon::now()->subDays($i)->toDateString() }}', item1: '{{ $transactions->whereDate('created_at', '=', 'Carbon'Carbon::now()->subDays($i)->toDateString())->where('status', 'C')->sum('amount') }}'},  
@endfor
{y: '{{ 'Carbon'Carbon::now()->toDateString() }}', item1: '{{ $transactions->where('created_at', '>=', 'Carbon'Carbon::now()->toDateString())->where('status', 'C')->sum('amount') }}'}

此外,如果我将任何值硬编码到图中,它可以很好地工作,因此应该排除任何jQuery问题。所以从本质上讲,似乎只有我第一次使用这个调用时它才有效。

我假设解决方案是清理碳/收款电话的数量(因为总共有60个),但我不太确定从哪里开始。我正在将来自控制器的集合作为"事务"传递。

结果:

{y: '2016-06-18', item1: '0'},
...
{y: '2016-07-15', item1: '0'},
{y: '2016-07-16', item1: '0'},
{y: '2016-07-17', item1: '0'},
{y: '2016-07-18', item1: '0'}

预期结果:

{y: '2016-06-18', item1: '0'},
...
{y: '2016-07-15', item1: '10.00'},
{y: '2016-07-16', item1: '0'},
{y: '2016-07-17', item1: '0'},
{y: '2016-07-18', item1: '0'}

尝试进行

with(clone $transaction)->query_here

您的查询可能会在整个循环中被覆盖/更改。

希望它能有所帮助!

我猜您有一些逻辑错误。无论如何,您不应该在视图中构建图形数据。相反,将逻辑放在控制器中,或者更好地放在演示者或服务类中。不过,就目前而言,把它放在控制器中就可以了。

试试这个,在你的控制器中,添加:

$graph = [];
$currentDay = 'Carbon'Carbon::now();
for ($i=0; $i < 30; $i++) {
    if ($i > 0) {
        // Subtract a day starting from the second loop
        $currentDay->subDay();
    }
    $dateString = $currentDay->toDateString();
    $currentDayData = [
        'y' => $dateString,
        'item1' => $transactions->whereDate('created_at', $dateString)->where('status', 'C')->sum('amount'),
    ];
    // Prepend to final array
    array_unshift($graph, $currentDayData);
}
$graph = json_encode($graph);
// Don't forget to export $graph to your view

然后在视图中,将JSON字符串放置在适当的data-*属性中。例如:

<div id="graph" data-graph="{{ $graph }}"></div>

最后,在.js文件中,您可以获取数据并从中构建图形:

// Note: You don't need to parse the JSON string manually
// since jquery will do that automatically in this case
const data = $('#graph').data('graph');
// Then feed the data into whatever graph API that you use

我还没有测试过这个代码,所以请告诉我它的进展情况。