【问题标题】:Yii2 ActiveRecord cacheYii2 ActiveRecord 缓存
【发布时间】:2015-04-24 18:26:29
【问题描述】:

如何在 Yii 2 中使用 ActiveRecotd 缓存?我在官方文档中没有找到任何示例。在 Google 我找到了 2 个例子,第一个是:

$db = self::getDb();
$object = $db->cache(function ($db) use($id) {
    return self::findOne($id);
});

但它不适用于Model,我使用更新的框架进行了测试。其他例子是:

$data = \Yii::$app->cache->get('some_var_' . $id);
if ($data === false)
{
    $data = self::findOne($id);
    \Yii::$app->cache->set('some_var_' . $id, $data, 60);
}

它工作正常,但不是 ActiveRecord 缓存它是数据缓存,所以我们在 Yii 2 中没有 ActiveRecord 缓存?

【问题讨论】:

    标签: caching activerecord yii yii2


    【解决方案1】:

    1) 像这样使用缓存:

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

    2)如果你可能使用查询依赖,那么使用:

    $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);
    

    【讨论】:

      【解决方案2】:

      我也遇到了这个问题。这是我暂时针对 hasOne() 关系的解决方法。

      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;
      }
      

      我只想缓存当前请求的数据,所以这行得通。但是因为我使用的是->one();,所以如果我们调用$model->getGroup()(我发现这对于扩展查询很有用),它不会返回 ActiveQuery 对象

      不幸的是,如果我确实返回了 ActiveQuery 对象,Yii2 会对其进行一些“魔术”,并且总是会执行我无法控制的 SELECT *。

      【讨论】:

      • 在 Yii AR 中,您可以使用: $model->getGroup() 获取 ActiveQuery 或 $model->group 获取 BillChangesGroup 对象(Yii2 magic ->group == getGroup()->one( )在你的例子中)。在您的解决方案中,您错过了这一点。
      • 感谢您的解决方案!
      【解决方案3】:

      从 2.0.14 开始,您可以使用以下快捷键:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-10
        • 1970-01-01
        相关资源
        最近更新 更多