Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rszabo@crowleyauto.net's avatar

Join with sub query in eloquent

I'm trying to get the running balance from a ledger. I am able to get the results I want from this query builder. But I need to pagainate the results and I don't see that paginate works on query builder. So I am trying to build the sql with eloquent, but I can't seem to figure out how to do it. Here is the current query builder. Thanks

$ledgers = DB::select(DB::raw('SELECT total_charge, payment_total, transaction_date, ledgers.id, jump_types.jump_name as jumpname,transaction_type,from_manifest_number, ROUND(@sum := @sum + total_charge - payment_total) AS running_bal FROM ledgers JOIN ( SELECT @sum:=:bal ) AS tx WHERE jumper_id = :id ORDER BY id'),['id'=>$id,'bal'=>$balance_forward->balance_forward]);

0 likes
3 replies
jlrdw's avatar

Here is a checkbook ledger with a running balance (not laravel, another framework) But sql is sql.

A running sum is a query in a query:

        $checksearch = $checksearch . "%";
        $pagingQuery = " LIMIT $offset, $rowsperpage";

        $sql = "SELECT OD.checkid, OD.transdate, OD.transdescribe, OD.widthdraw, OD.deposit, OD.isclr,";
        $sql = $sql . " (SELECT (Sum(IFNULL(deposit, 0)) - Sum(IFNULL(widthdraw, 0))) FROM checks";
        $sql = $sql . " WHERE checkid<=OD.checkid) AS RunningSum";
        $sql = $sql . " FROM checks AS OD" . $pagingQuery;
        $sth = $this->db->pdoPrepare($sql);
        //$sth = $conn->prepare($sql);
        $sth->execute();
        $results = $sth->fetchAll(\PDO::FETCH_ASSOC);
        return $results;

Notice the AS RunningSum

I would highly recomment you go here https://www.mysqltutorial.org/ And take some tutorials on queries, as a running sum is just a basic query.

Use a length aware paginator: https://laracasts.com/discuss/channels/guides/manual-pagination-episode-3

rszabo@crowleyauto.net's avatar

Thanks for the quick response. The sql I currently have works just fine. I'm looking to convert it to a laravel eloquent request so I can use some of the laravel built in methods like pagination. Thanks

Please or to participate in this conversation.