valdanny
(Valdanny)
October 29, 2013, 9:00am
1
Hi, maybe someone can help:
i’m following this: http://www.yiiframework.com/doc/guide/1.1/en/caching.data
$dependency = new CDbCacheDependency(‘SELECT MAX(update_time) FROM tbl_post’);
$posts = Post::model()->cache(1000, $dependency)->findAll();
my questions are:
is the query fetched from the cache if exist or only stored with this procedure?
If the dependency is evaluated every time by querying the database where is the offload from the databse (it will get hit every time anyway…?)
Thanks,
Danny
Keith
(Kburton)
October 30, 2013, 9:29am
3
I suppose the benefit occurs if the query that checks whether the cache is still valid is much simpler than the query that generates the cache. In that case, you may be hitting the database every time, but the query might run faster and lock fewer rows, so reducing database contention.
Keith
(Kburton)
October 30, 2013, 9:31am
4
With regard to your first question, I think it’s very clearly explained in the guide:
Using Query Caching with DAO
To use query caching, we call the CDbConnection::cache() method when we perform DB queries. The following is an example:
$sql = ‘SELECT * FROM tbl_post LIMIT 20’;
$dependency = new CDbCacheDependency(‘SELECT MAX(update_time) FROM tbl_post’);
$rows = Yii::app()->db->cache(1000, $dependency)->createCommand($sql)->queryAll();
When running the above statements, Yii will first check if the cache contains a valid result for the SQL statement to be executed. This is done by checking the following three conditions:
if the cache contains an entry indexed by the SQL statement.
if the entry is not expired (less than 1000 seconds since it was first saved in the cache).
if the dependency has not changed (the maximum update_time value is the same as when the query result was saved in the cache).
If all of the above conditions are satisfied, the cached result will be returned directly from the cache. Otherwise, the SQL statement will be sent to the DB server for execution, and the corresponding result will be saved in the cache and returned.