2016-05-16 86 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();