Don't Query Db When Page Is Cached

Hi,

in my SiteController in actionIndex, I do something like this:


$places = Place::model()->findAllByAttributes(array('top'=>1));

$this->render('index', array('places' => $places);

Now, in the index view, I use


<?php if($this->beginCache('index_view', array('duration'=>86400))): ?>

...

<?php foreach($places as $place): ?>

  <?php echo $place->foreign_user->name; ?>

<?php endforeach;

...

<?php $this->endCache(); endif; ?>

and so on. My problem is, that if the view is already cached, the Controller will still do the findAllByAttributes and query the SQL, although it won’t be needed in the view, as it comes from the cache.

How could I make the controller check whether the view is cached and then skip all queries?

Well, data/query caching works independently from fragment caching. There are situations where it can make sense to combine those caching methods. However, my impression is that you should resort to query caching exclusively in your case. Pay special attention to the subsection "Using Query Caching with ActiveRecord."

…or you can use data provider pattern which prepares query but do not execute it unless there is real need to fetch data.

the difference is that with dataprovider whole rendered HTML part will be cached, and with query cache it will be still rendered on every request. It is important when you use lazy loading.

Thanks for your replies.

I will use query caching first. Building the site isn’t very CPU consuming, but I want to decrease the amount of queries.

So be careful with lazy loading, which you are using - you are printing “$place->foreign_user->name”, but you did not query for Places::model->with(‘foreign_user’). This way you will stil have queries for each ‘foreign_user’ sparately…