Yii关系查询与MySQL的SUM

时间:2015-07-24 20:58:39

标签: php mysql yii

在使用关系查询的Yii 1.1.x中,请考虑以下表格:

表'发票'

id, original_balance, invoice_date, due_date

表'InvoicePayments'

id, invoice_id, payment_amount, old_balance, new_balance, payment_date

模态invoice.php function relations()

'Payments' => array(self::HAS_MANY, 'InvoicePayments', array( 'id' => 'invoice_id' )

如果我想对特定的Invoice对象使用关系查询,我该如何获得所有SUM的{​​{1}}?

示例(不起作用):

InvoicePayments.payment_amount

我发现如果没有这个,我必须在没有$model = Invoice::model()->with( array( 'InvoicePayments' => array( "??.SUM(payment_amount) )->findByPk(1);的情况下提取关系查询并循环遍历每个SUM以获得支付给发票的总金额。

感谢您的帮助,感谢您的帮助

1 个答案:

答案 0 :(得分:1)

使用有效记录提供的http://www.sitecore.net/learn/blogs/technical-blogs/sitecore-magnified/posts/2013/09/ecm-on-cd.aspx,并通过指定选择选项强制它使用Statistical Query STAT

invoice.php:

public function relations()
{
    return array(
        'payments' => array(self::HAS_MANY, 'InvoicePayments', array( 'id' => 'invoice_id' )
        'paymentsSum'=>array(self::STAT, 'InvoicePayments', 'invoice_id', 'select' => 'SUM(payment_amount)'),
    );
}

然后,您可以使用它来加载一个或多个模型,使用任何 lazy 渴望方法,这里有3个不同的例子:

// the lazy loading approach
$invoice=Invoice::model()->findByPk(10);
$total = $invoice->paymentsSum;

// the eager loading approach
$invoices=Invoice::model()->with('paymentsSum')->findByPk(10);
$total = $invoice->paymentsSum;

// the eager loading approach to load all invoices
$invoices=Invoice::model()->with('paymentsSum')->findAll();
$total_of_invoice_10 = $invoices[10]->paymentsSum;