Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Best practice for finding sum-values of related models-array
  • Hello,

    I have the following situation:

    class Model_Customer extends \Orm\Model  {
    protected static $_has_many = array(
    'invoices' => array( 'model_to' => 'Model_Invoice', )
    );
    }

    class Model_Invoice extends \Orm\Model  {
    protected static $_properties = array(
    ....
    'value'
    );
    }

    Now I want to get the sum of the invoice-values of one customer.
    The following code would work, but it is the best way (performance)?

    $sum = 0;
    foreach( $this->invoices AS $invoice ) {
    $sum += $invoice->getNetto();
    }



  • HarroHarro
    Accepted Answer
    It depends, you'll have to test it.

    You should make sure "invoice" is included in the query (using related), to avoid a second query due to lazy loading. And compare the additional impact of the join (and the loop) with a separate SUM query.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion