JKofsky
JKofsky

Reputation: 125

Yii2 - How to cache a Database query

I have read many of the posting on this on here, and the Docs, but still am having problems figuring out how to do what I want.

I am using a GridView with dropDown filters. I currently have the following code in my AudioModel to get the selection array:

Public function getFeednameSelect() {
   return ArrayHelper::map(
             Audio::find()
                ->select('feedname')
                ->distinct()
                ->asArray()
                ->all(),
             'feedname', 'feedname'),
}

web\config.php contains

$config = [
    ...
    'components' => [
        ...
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
    ...

The AudioModel currently has over 83k records. I would like to

This is my first attempt at caching anything.

Thank you.

---UPDATE --- I have tried the following

    public function getFeednameSelect() {
        $duration = 86400;     // cache query results for 1 day (60*60*24 secs).
        $dependency = [
            'class' => 'yii\caching\DbDependency',
            'sql' => 'SELECT MAX(`modifieddatetime`) FROM `feeds`',
        ];

        return ArrayHelper::map(
                        $this->find()
                                ->select('feedname')
                                ->orderBy('feedname')
                                ->distinct()
                                ->asArray()
                                ->cache(15)                         // This works
                                //->cache($duration, $dependency)   // This doesn't
                                ->all(),
                        'feedname', 'feedname');
    }

When I use ->cache($duration, $dependency) I keep getting

Call to a member function evaluateDependency() on array

The $this->find() works. The fieldname and tablename in the 'sql' => statement are correct.

Upvotes: 1

Views: 152

Answers (1)

Jap Mul
Jap Mul

Reputation: 18769

Almost there. I think the only thing you have to change is

$dependency = [
    'class' => 'yii\caching\DbDependency',
    'sql' => 'SELECT MAX(`modifieddatetime`) FROM `feeds`',
];

into

$dependency = new DbDependency();
$dependency->sql = 'SELECT MAX(`modifieddatetime`) FROM `feeds`';

Right now you are passing the dependency as an array, which would explain the error. The dependency needs to be an object, one that extends the caching dependency class.

Upvotes: 1

Related Questions