牛骨文教育服务平台(让学习变的简单)
博文笔记

CDbCacheDependency关于复杂的sql

创建时间:2013-12-20 投稿人: 浏览次数:1174

CDbCacheDependency关于复杂的sql


写CDbCacheDependency的sql时的原则是:这条sql必须是轻量级的,因为他在每次读取cache时都会执行一遍他。

一般写CDbCacheDependency的sql时习惯用
$dependecy = new CDbCacheDependency("SELECT MAX(update_time) FROM tbl_question");

$dependecy = new CDbCacheDependency("SELECT AVG(update_time) FROM tbl_question");

注意:用avg代替max的好处是可以判断出删除时的变化。

原文如下:
I remember now why you should use AVG and NOT MAX.
If you have something like:
$dependency=new CDbCacheDependency("SELECT MAX(last_updated) FROM {{post}}");
$criteria=new CDbCriteria;
$criteria->order="post_id DESC";
$models=self::model()->cache(1000,$dependency)->findAll($criteria);
foreach($models AS $model){
echo $model->title;
}
And let"s say the above query returns 10 models, all 10 models will be cached for the next requests, but if you delete one of those 10 records from the database (not the last updated one, on which the depenency is created on by using MAX()) then in frontend you will still receive 10 models, when in fact the cache should invalidate and you should retrieve 9 models.

注意:可以用CGlobalStateCacheDependency 代替CDbCacheDependency,可以用CGlobalStateCacheDependency 来存储last create, update or delete time of a table in a global state, 然后用他来检验dependency 的变化,不过这样容易出错

参考:http://www.yiiframework.com/forum/index.php?/topic/11394-cdbcachedependency-and-cactivedataprovider/
http://www.yiiframework.com/forum/index.php/topic/33449-cdbcachedependency-subsequvent-calls/page__p__161165#entry161165‘

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。