简体   繁体   中英

Doctrine 1.2 calculating the sum of oneToMany relations with DQL

Using doctrine 1.2 I'm trying to do the following.:

lets say I have a model Job which has many Invoice(s).

In my invoice model I have a DQL event listener like

public function preDqlSelect(Doctrine_Event $event)
{
    $q = $event->getQuery();
    $q->addSelect('(hours * local_rate) as invoice_payout');
    $q->addSelect('(hours * global_rate) as invoice_bill');
    $q->addSelect('((hours * global_rate) - (hours * local_rate)) as invoice_profit');
}

which works fine, also to note the above is calculated as needed because depending on the user asking for it, it needs to be calculated differently.

The issue I am having is trying to do something like the following:

Select Job and foreach job->invoices SUM('invoice_payout) as job_payout, SUM('invoice_bill) as job_bill, SUM('invoice_profit') as job_profit.

I know the above is in no way correct syntax, but it was the best way I could explain what I was after.

"invoice_payout" and "invoice_bill" do not physically exist in the table. You need to use the columns from the table. Try this:

public function preDqlSelect(Doctrine_Event $event)
{
    $q = $event->getQuery();
    $q->addSelect('SUM(hours * local_rate) as job_payout');
    $q->addSelect('SUM(hours * global_rate) as job_bill');
    $q->addSelect('SUM((hours * global_rate) - (hours * local_rate)) as job_profit');
    $q->groupBy('job_id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM