Query Caching

Can someone explain how to use query caching in Yii 2.0?

In Yii 1.x i used this:


Setting::model()->cache(86400)->findAll();

for example. How does this looks like in Yii 2?

Anyone an idea?

Not used it yet and the Yii docs/guide are not yet complete for caching.

You probably need to first set [font="Courier New"]enableQueryCache[/font] to true for your [font="Courier New"]db[/font] parameter in your Yii Config file.

Yes, that’s why i asked it here ;-). When i set enableQueryCache to true it indeed enable caching for queries, but it does this for ALL queries (what i definitely don’t want)

If you do not want it globally, one way to do it is if when you instantiate the db connection… like below. Definitely there should be other ways with ActiveRecord… but a quick dirty example below if you are using DB Connections (not tested this though):




$conn = \Yii::$app->db;


/* Cache setups */

$conn->enableQueryCache = true;

$conn->queryCacheDuration = 36000; // Optional: Set your cache duration

$conn->queryCache = 'cache'; // Optional: Set your cache component

$conn->queryCacheDependency = $dependency; // Optional: Set your cache dependency


/* Define and execute the query */

$command = $conn->createCommand('SELECT * FROM tbl_post');

$posts = $command->queryAll();