I have news table and its related news_comment table. I have defined relation newsComment with news_comment table.
If I execute this query:
$result = News::getDb()->cache(function () use($id) {
return News::find()->with('newsComment')->where(['news.id' => $id])->one();
});
Only query that is fetching data from news table will be cached. Query that is selecting from related table is not.
Is it possible to cache both main query and queries executed to retrieve data from related tables together, without having to write them separately ?
Try This:
$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;
});
Try to add $db
or Yii::$db
as a param:
$result = News::getDb()->cache(function ($db) {
return News::find()->with('newsComment')->where(['news.id' => $id])->one();
});
Or add the cache in the query itself:
$result = News::find()->with('newsComment')->where(['news.id' => $id])->cache(60)->one();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With