使用laravel eloquent计算(总分类帐)

AAl*_*suf 2 php mysql sql laravel eloquent

我知道使用雄辩可能很难实现,但我似乎并没有放弃它不可能的想法.

我有一个叫做finances部分结构的表:

amount (float) 
type(varchar) - can take either "credit" or "debit"
date(date)
Run Code Online (Sandbox Code Playgroud)

现在,我想要的是:在每次交易后计算"余额"样本:

       Type    Amount   Balance   Date(dd/m/yyyy)  
--- -------- -------- --------- ----------------- 
1   credit   5.00     25.00     12-1-2014        
2   debit    10.00    20.00     11-1-2014        
3   debit    5.00     10.00     10-1-2014        
4   credit   15.00    15.00     09-1-2014        
Run Code Online (Sandbox Code Playgroud)

你有什么建议使用Eloquent?

luk*_*ter 5

这个答案启发了SQL魔术

它看起来不是很漂亮但很有效.或者,您可以考虑使用余额选择创建数据库视图,以使代码更清晰.

Finance::select('id', 'amount', 'type', 'date',
                DB::raw('@balance := @balance + IF(type = "credit", amount, -amount) AS balance'))
         ->from(DB::raw('finances, (SELECT @balance := 0) AS balanceStart'))
         ->get();
Run Code Online (Sandbox Code Playgroud)

使用分页

因为paginate()只会查询部分记录(因此返回不正确的余额),你必须自己进行分页......等等.您仍然可以使用该Paginator课程.

$allFinances = // query from above
$perPage = 10;
$pagination = App::make('paginator');
$count = $allFinances->count();
$page = $pagination->getCurrentPage($count);
$finances = $this->slice(($page - 1) * $perPage, $perPage)->all();
$items = $pagination->make($items, $count, $perPage);

// pass $items to the view
Run Code Online (Sandbox Code Playgroud)

  • 是啊,然后balancestart将是当前页面中的第一个元素,而不是整个表格(意味着它将从错误的数字开始计数)@lukasgeiter (2认同)