Yii2 ActiveRecord cache

后端 未结 3 1221
春和景丽
春和景丽 2020-12-17 03:03

How to use ActiveRecotd cache for Yii 2? I did\'t find any examples in official docs. In Google I found 2 examples, first is:

$db = self::getDb();
$object =          


        
相关标签:
3条回答
  • 2020-12-17 03:39

    1) Use cache like that:

    $db = Yii::$app->db;// or Category::getDb()
    $result = $db->cache(function ($db) use ($id) {
        return Category::find()->where(['id' => $id])->all();
    }, CACHE_TIMEOUT);
    

    2) If you may use query dependency, use like that:

    $db = Yii::$app->db;// or Category::getDb()
    $dep = new DbDependency();
    $dep->sql = 'SELECT count(*) FROM category';
    $result = $db->cache(function ($db) use ($id) {
        return Category::find()->where(['id' => $id])->all();
    }, CACHE_TIMEOUT, $dep);
    
    0 讨论(0)
  • 2020-12-17 03:40

    Since 2.0.14 you can use the following shortcuts:

    (new Query())->cache(7200)->all();
    // and
    User::find()->cache(7200)->all();
    

    Source: https://www.yiiframework.com/doc/guide/2.0/en/caching-data

    0 讨论(0)
  • 2020-12-17 03:45

    I too am having trouble with this. Here's my workaround for the time being for a hasOne() relationship.

    public function getGroup()
    {
        if(isset(static::$_getGroup[$this->id])) {
            return static::$_getGroup[$this->id];
        }
        $Group = $this->hasOne(BillChargesGroup::className(), ['id' => 'group_id'])->one();
        static::$_getGroup[$this->id] = $Group;
        return $Group;
    }
    

    I only want to cache data for the current request, so this works. However because I'm using ->one(); it does not return the ActiveQuery object if we call $model->getGroup() (which I found is good for extending queries)

    Unfortunately if I do return the ActiveQuery object, Yii2 does some "magic" on it and always does a SELECT * which I can't control.

    0 讨论(0)
提交回复
热议问题