V
V
Vladimir Golubev2015-06-20 17:33:36
MySQL
Vladimir Golubev, 2015-06-20 17:33:36

How to set up caching in Yii2 in a relation method? And is it possible?

Code in the class:

public function getRoutes()
    {
        return $this->hasMany(Route::className(), ['place_id' => 'id']);
    }

I'm trying to cache like this:
$db = self::getDb();
return $db->cache(function ($db){
        return $this->hasMany(Route::className(), ['place_id' => 'id']);
});

It doesn't throw any errors, but it doesn't cache the result either.
Found this thing on the Internet:
return $this->hasMany(Route::className(), ['place_id' => 'id'])->cache(60)->all();

But it returns an error, even though that would be the most convenient use of caching...
UPD:
managed to cache from outside:
$place = Place::getDb()->cache(function ($db) use($hero) {
return Place: :find()->where(['id' => $hero->location_id])->with('filteredRoutes')->asArray()->all();
}, 600);
However, I want to add additional filters to the relation, and I'm not sure that they will be taken into account correctly...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vyachin, 2015-06-21
@wladyspb

It is impossible to do this in the current version of the framework. It is better to move caching above the data retrieval layer and the higher the better. Good option www.yiiframework.com/doc-2.0/guide-caching-fragmen...

D
Denis Shpuganich, 2018-05-04
@dyonis

I'm still just learning too, but this is how it works for me exactly as it should:
The number of requests on list pages has been halved (username is displayed on each line).
True, I'm not sure that this is correct in terms of performance (a debatable question is who will be faster: a file cache or a database that also caches the same requests)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question