【问题标题】:Calculate (General ledger like) using laravel eloquent使用 laravel eloquent 计算(类似总账)
【发布时间】:2015-02-27 00:19:48
【问题描述】:

我知道使用 eloquent 可能很难实现,但我似乎并没有放弃它做不到的想法。

我有一个名为finances 的表,部分结构:

amount (float) 
type(varchar) - can take either "credit" or "debit"
date(date)

现在,我想要的是:在每次交易后计算“余额” 示例:

       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        

您对使用 Eloquent 有什么建议?

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案1】:

    this answer启发的SQL魔法

    它看起来不是很漂亮,但很有效。或者,您可以考虑使用 balance select 创建一个 db 视图,以使您的代码更简洁。

    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();
    

    使用分页

    因为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
    

    【讨论】:

    • 这看起来棒极了!谢谢,如果我想使用 ->paginate() 怎么办?
    • @AAlyusuf 应该可以正常工作。只需将->get() 替换为->paginate()
    • 是的,但是 balancestart 将是当前页面中的第一个元素,而不是整个表格(意味着它将从错误的数字开始计数)@lukasgeiter
    • 这种情况下如何使用join?
    猜你喜欢
    • 1970-01-01
    • 2019-12-23
    • 2013-07-27
    • 1970-01-01
    • 2016-08-12
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多