2016-05-16 91 views
7

我有新闻表及其相关的news_comment表。 我用news_comment表定义了关系newsComment。Yii2:如何缓存由ActiveRecord关系作出的查询

如果我执行这个查询:

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

是从消息表中读取的数据将被缓存只有查询。从相关表中选择的查询不是。

是否有可能缓存主查询和查询执行从相关表检索数据在一起,而不必分别写入它们?

+0

你试图使用'joinWith'? http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations –

+0

@PatrykRadziszewski是的,它没有任何区别。 – offline

+0

这应该工作(几周前已经尝试过),告诉我们你是如何检查相同的查询被执行2次? – soju

回答

2

试试这个:

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

}); 
0

尝试添加$dbYii::$db作为PARAM:

$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();