Question

In SilverStripe I want to calculate the sum of only the first three DataObjects, to get a sub amount.

I tried the following but the function always returns the sum of all DataObjects and not only the first three.

public function getSubSum() {
    $service = ServiceProvided::get()->filter(array(
        'InvoiceObjectID' => $this->ID
    ));
    $sum = $service->limit(3, 0)->sum('Sum');
    return $sum;
}

How do I calculate the sum of only the first three DataObjects?

Was it helpful?

Solution 2

To calculate the sum in PHP use a for loop to go through each database row returned, and add the value to a variable.

public function getSubSum() {

    $services = ServiceProvided::get()
        ->filter('InvoiceObjectID', $this->ID)
        ->limit(3, 0);

    $sum = 0;

    foreach($services as $service) {
        $sum += $service->Sum;
    };

    return $sum;
}

OTHER TIPS

The SUM is calculated first, and and then the limit is applied after the aggregate sum function has already been calculated. In effect you're asking it to calculate the sum first, which returns a single row, and then limit that result to three rows.

To do this you will probably need to use a subquery like:

SELECT SUM("Sum") FROM (SELECT "Sum" FROM "ServiceProvided" WHERE ... LIMIT 3)

To execute custom SQL in SilverStripe you can use DB::query(). However, you need to be careful when doing this to avoid SQL injection. A simpler approach would just be to calculate the sum in PHP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top