0

I don't know if I'm not holding my toungue right or something, but I'm trying to get a total in the table footer. I have no doubt there is something I'm missing, here is what I tried:

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get()->sum('labor');

Which works well up until here:

->sum('labor')

Then I get:

Call to undefined method Illuminate\Database\Eloquent\Collection::sum()

So I'm obviously using it incorrectly because it's in the docs here:

http://four.laravel.com/docs/queries

Some feedback would be much appreciated. :)

I think this might actually be relevant:

public function index()
{
    $labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

    return View::make('labors.index', compact('labors'));
}
4

3 回答 3

3

你需要做两件事:

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();

上面获取了用于 foreach 的数组。

$laborTotal = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

这得到了总数。那么您需要做的就是将它们都发送到视图中,然后在表的页脚中使用总数:

return View::make('labors.index', compact('labors', 'laborTotal'));

查看类似:

@foreach ($labors as $labor)
<tr> ... </tr>
@endforeach
<tr><td>{{ $laborTotal }}</td></tr>
于 2013-10-09T21:11:01.933 回答
1

如果你需要做一个 foreach,你将不得不做 2 个查询:

$total = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();

这是因为 sum() 返回一个带有总和的整数,而不是一个集合。

于 2013-10-09T21:00:56.883 回答
1

很确定应该是

$labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');

这是根据您正在查看 Fluent 文档的Eloquent Aggregates

您现在不需要compact$labors,因为它是字符串而不是数组

于 2013-10-09T21:01:09.530 回答