CakePHP:复杂查询的分页

时间:2013-03-03 04:47:13

标签: pagination cakephp-2.1

我有3个表:帐户,交易,报表。帐户有很多交易&语句(外键是account_id)。

我需要检索account_name,结算交易余额,总计&所有具有未结余额和/或未结算交易的账户的未开单(待定)交易和最后一个账单日期的计数。

此查询按预期返回数据:

SELECT 
    Account.id, Account.account_name, 
    Billed.balance, Pending.items, 
    Pending.amount, Stmnt.latest 
FROM 
    accounts as Account
LEFT JOIN
    (SELECT
        account_id, 
        (SUM(`Transaction`.`debit`) - SUM(`Transaction`.`credit`)) as balance
    FROM
        `transactions` AS `Transaction`
    WHERE
        `Transaction`.`statement_id` > 0 AND
        `Transaction`.`void` = 0
    GROUP BY
        account_id
    ) AS Billed ON Billed.account_id = Account.id
LEFT JOIN
    (SELECT
        `account_id`, 
        (SUM(`Transaction`.`debit`) - SUM(`Transaction`.`credit`)) as amount, 
        COUNT(id) AS items
    FROM
        `transactions` AS `Transaction`
    WHERE
        `Transaction`.`statement_id` = 0 AND
        `Transaction`.`void` = 0
    GROUP BY
        account_id
    ) AS Pending ON Pending.account_id = Account.id
LEFT JOIN
    (SELECT
        `account_id`, 
        MAX(Statement.statement_date) AS latest
    FROM
        `statements` AS `Statement`
    WHERE
        `Statement`.`void` = 0
    GROUP BY
        account_id
    ) AS Stmnt ON Stmnt.account_id = Account.id
GROUP BY
    account.id
HAVING
    Billed.balance > 0 OR
    Pending.pending_ct > 0
ORDER BY
    account_name ASC

我很难将其成功转换为CakePHP 2.1查找或分页友好选项。

任何想法都会非常感激。

0 个答案:

没有答案