off*_*ine 9 php activerecord caching query-cache yii2
我有新闻表及其相关的news_comment表.我已经使用news_comment表定义了关系newsComment.
如果我执行此查询:
$result = News::getDb()->cache(function () use($id) {
return News::find()->with('newsComment')->where(['news.id' => $id])->one();
});
Run Code Online (Sandbox Code Playgroud)
只缓存从新闻表中获取数据的查询.从相关表中选择的查询不是.
是否可以缓存执行的主查询和查询以从相关表中检索数据,而无需单独编写它们?
尝试这个:
$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;
});
Run Code Online (Sandbox Code Playgroud)