使用碳过滤器对刀片模板中的Eloquent收集产生奇怪的结果

时间:2016-07-18 21:47:57

标签: php laravel eloquent blade php-carbon

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

我正在构建过去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'。

情侣注意事项:如果我在3天前做出FIRST输出',则返回预期值。例如:

{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'}

2 个答案:

答案 0 :(得分:0)

尝试做

with(clone $transaction)->query_here

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

希望它有所帮助!

答案 1 :(得分:0)

我猜你有一些逻辑错误。无论如何,您不应在视图中构建图形数据。而是将逻辑放在控制器中,或者更好地放在演示者或服务类中。但是现在,将它放在你的控制器中就可以了。

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

$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

我没有测试过这段代码,所以请告诉我它是怎么回事。