我有新闻表及其相关的新闻评论表。 我已经用 news_comment 表定义了关系 newsComment。
如果我执行这个查询:
$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;
});
关于php - Yii2:如何缓存 ActiveRecord 关系所做的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37253824/