gpt4 book ai didi

php - Yii CActiveDataProvider 查询缓存无法正常工作

转载 作者:搜寻专家 更新时间:2023-10-31 21:11:36 24 4
gpt4 key购买 nike

我想缓存 CActiveDataProvider 实例的数据库结果。

我在 Controller 的操作中准备数据提供者,然后在 CGridView 中使用数据提供者,稍后在某些 View 中使用。

我曾经有过这样的代码:

$cars=new CActiveDataProvider(
'Car'
,
array(
'criteria'=>array(
'condition'=>'brand_id=:brand_id',
'params' => array(':brand_id'=>$model->id),
'order' => 'price',
),
'pagination'=>false,
)
);

然后,在 tutorial in the yii wiki 之后,我改成了:

$cars=new CActiveDataProvider(
Car::model()->cache(3600)
,
array(
'criteria'=>array(
'condition'=>'brand_id=:brand_id',
'params' => array(':brand_id'=>$model->id),
'order' => 'price',
),
'pagination'=>false,
)
);

但无济于事:查询未被缓存。

最佳答案

CActiveDataProvider 的优点之一是查询不会立即执行。只有当您稍后使用 CActiveDataProvider 时才会执行查询,比如在 CGridView 中,它将调用 CActiveDataProvider::fetchData最终触发查询。

这很有用,因为您可以使用片段缓存,并且您不希望在 Controller 中加载数据只是为了发现您不需要它,因为片段已被缓存。

这正是这里发生的事情:ActiveRecord ->cache() method指示 DB Connection 缓存后续查询,但如果查询没有立即执行,则可能在此查询之前执行其他查询,并且此缓存将不起作用。

我解决了创建个性化 ActiveDataProvider 的问题,它将在查询发生之前设置模型缓存:

class CachedActiveDataProvider extends CActiveDataProvider
{

public $cache_duration = null;
public $cache_dependency = null;

/**
* The cache mechanism works by telling the DB Component to cache the next query.
* When fetchData() is called, the DB will cache the next query.
* There is a possibility that fetchData call calculateTotalItemCount()
* and in that function, if this bit is active, we will tell the DB to cache
* 2 queries, the count, and the actual fetch that will come next.
* (if we don't do this, the DB will cache the count query, and will forget about
* the instruction to cache the fetch query)
*
* @var boolean
*/
private $fetching_data = false;

protected function fetchData()
{
if (!is_null($this->cache_duration ))
{
$this->model->cache($this->cache_duration, $this->cache_dependency);
}

$this->fetching_data = true;
$ret = parent::fetchData();
$this->fetching_data = false;

return $ret;
}

protected function calculateTotalItemCount()
{
if (!is_null($this->cache_duration ))
{
$this->model->cache(
$this->cache_duration,
$this->cache_dependency,
$this->fetching_data ? 2 : 1 //if fetching data, cache 2 queries: this count and the sequent fetching
);
}

return parent::calculateTotalItemCount();
}
}

我现在可以调用它了

$cars=new CachedActiveDataProvider(
'Car'
,
array(
'criteria'=>array(
'condition'=>'brand_id=:brand_id',
'params' => array(':brand_id'=>$model->id),
'order' => 'price',
),
'pagination'=>false,
'cache_duration' => 3600,
)
);

关于php - Yii CActiveDataProvider 查询缓存无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com