Yii2 ActiveRecord的缓存 [英] Yii2 ActiveRecord cache

查看:582
本文介绍了Yii2 ActiveRecord的缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ActiveRecotd缓存的Yii 2?余did't找到官方文档的任何实例。在谷歌,我发现两个例子,第一个是:

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 = $db->cache(function ($db) use($id) {
    return self::findOne($id);
});

不过,对于型号,我用最新的框架测试不起作用。其他的例子是:

But it doesn't work for Model, I tested with updated framework. Other example is:

$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的缓存是数据缓存,所以我们还没有得到ActiveRecord的缓存中的Yii 2?

It's working fine, but it's not ActiveRecord caching it's data caching, So we haven't got ActiveRecord caching in Yii 2?

推荐答案

我也是有这个麻烦。这里是我的解决方法暂时的hasOne()的关系。

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

我只想缓存数据为目前的要求,所以这个工程。但是,由于我使用 - - 酮(); 它不会返回ActiveQuery对象,如果我们称之为 $建模> getGroup() (我发现有利于扩大查询)

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)

不幸的是,如果我做回了ActiveQuery对象,Yii2做了一些它的神奇,始终做一个SELECT *这是我无法控制的。

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

这篇关于Yii2 ActiveRecord的缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆