lot
lot

Reputation: 1491

How to fetch subquery columns in Phalcon

what would be the best way (or any way, because I can't figure out anything blending with Phalcon models at the moment) to fetch data from query like this:

SELECT *, (select sum(l.log_volume) from logs l where l.parcel_id = p.parcel_id) as parcel_total_volume 
FROM PARCELS p

what I want is to basically have calculated fields easily accessible from model, preferably calculated on sql side and fetched with every record.

If this must be done in model php code instead, then how?

Upvotes: 0

Views: 904

Answers (1)

cvsguimaraes
cvsguimaraes

Reputation: 13240

I would go for something like this:

<?php

class Parcels extends Phalcon\Mvc\Model
{
    private static $sumsCache = [];

    /*
       ...
    */

   public function getTotalVolume()
   {
        if(!isset($sumsCache[$this->parcel_id])) {
            $sumsCache[$this->parcel_id] = Logs::sum("parcel_id = $this->parcel_id");
        }

        return $sumsCache[$this->parcel_id];
   }
}

This way you fetch the sum JIT and you store a static cache for each parcel_id.

Upvotes: 3

Related Questions