Yii2:如何缓存ActiveRecord关系的查询


Yii2: How to cache queries made by ActiveRecord relations

我有新闻表及其相关的news_comment表。我定义了newsComment与news_comment表之间的关系。

如果我执行这个查询:

$result = News::getDb()->cache(function () use($id) {
    return News::find()->with('newsComment')->where(['news.id' => $id])->one();
});

只有从新闻表中获取数据的查询才会被缓存。从相关表中选择的查询不是。

是否可以同时缓存主查询和为从相关表中检索数据而执行的查询,而不必分别写入它们?

试试这个:

$db = News::getDb();
$result = $db->cache(function ($db) use ($id) {
  $query = new 'yii'db'Query;
  $query->select("news.*,newsComment.*") // write table name for newsComment model and also in join
        ->from('news')
        ->leftjoin('newsComment','newsComment.id=news.product_id')
        ->where(['news.id' => $id])
        ->one();
  $command = $query->createCommand();
  $result  = $command->queryAll();
  return $result;
});

尝试添加$dbYii::$db作为参数:

$result = News::getDb()->cache(function ($db) {
    return News::find()->with('newsComment')->where(['news.id' => $id])->one();
});

或者在查询中添加缓存:

$result = News::find()->with('newsComment')->where(['news.id' => $id])->cache(60)->one();