We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to use ORM cache in aggregate methods like sum, count etc.?

Hello everyone,

great result sets caching possibilities described in official docs

but how to use a cache for count method of a model? I tried the following but no luck

public function getPosition() {

        return self::count(["id<={$this->getId()}", 'cache' => ['lifetime' => 3600, 'key' => 'zz']]);

I know i can inmplement some kind of 'cache' manually, but how to do it using the framework, just like we do it for find(), findAll() and model relations?


If you are wanting to grab numbers then maybe just creating a seperate cache and giving it a key would be the way to go. Especially as you are only holding on to a number: https://docs.phalcon.io/en/latest/reference/cache.html#file-backend-example


Of course i can cache all the numbers i have wherever i want)). But i was interested in how to do it 'natively', exactly like we all do it using 'cache' key in 'find' method, for example. I thought that 'find', 'findAll', 'count' and so on are just good & recommended Phalcon Model methods, so why 'count' is ignored by the framework and have not got any caching possibility? If you have a hard condition and millions of rows in the table, 'count' can run during minutes, so i think that there is no sense to ignore the caching of 'count' (and other aggregate functions) at framework's level.


O i c. I mis-read the question there. Sorry about that. I would have expected that a slight deviation (see below) from https://docs.phalcon.io/en/latest/reference/models-cache.html#forcing-cache would have worked but I have not had the chance or situation yet to try it.

    // Cache the resultset for only for 5 minutes
    $products = Products::count(array(
        "cache" => array("key" => "my-cache", "lifetime" => 300)

If not then I suppose it's down to it being a new framework and it is something that is on the horizon.


Hey, you've suggested to try exactly what i have already tried in the first message of the topic, but i just used short array syntax ( [] instead of 'array'). So, it does not work. It looks like a great and really easy feature for the future releases. Feature request can be found here https://github.com/phalcon/cphalcon/issues/2401


Sorry, I'm not implying that you try it I just wanted to talk about how it's a natural assumption that it would work. :)