CakePHP’s invisible query cache

I just wanted to document something that was driving me nuts in Cake PHP.

I do a simple find on a model:

$thing = $this->Model->find(array('id' => 123), NULL, NULL, 1);

Then later on, I make the same query again. Only the first query appears in the SQL debug output. Why call it again? Well, I’ve made some manual queries in between the calls using SQL that is inconvenient to emulate in Cake functions, in particular INSERT IGNORE. It turns out that Cake has a largely undocumented query cache, but Cake has no idea that its cache is dirty because of the manual queries. The _clearCache function is not yet implemented for the query cache, so the only choice is to disable it before the first query, and you can do that during a single instantiation by saying:

$this->Model->cacheQueries = false;

Note that the query has 1 level of recursion, which means that all the sub-queries are also cached. Setting cacheQueries to false on this one model means that all queries through it don’t get cached, including those that may be in other models via relationships.

Leave a Reply

Your email address will not be published. Required fields are marked *