[英]Phalcon\Mvc\Models - model relationship and caching
Phalcon文檔中有以下內容:
http://docs.phalconphp.com/en/latest/reference/models.html#taking-advantage-of-relationships 。
假設我有這樣的代碼:
public function initialize()
{
$this->hasMany("id", "RobotsParts", "robots_id");
}
/**
* Return the related "robots parts"
*
* @return \RobotsParts[]
*/
public function getRobotsParts($parameters=null)
{
return $this->getRelated('RobotsParts', $parameters);
}
我想知道什么是最好的方法來緩存生成的“ -> getRelated() ”查詢嗎? 這意味着,如果多次調用它,則不應將其轉到數據庫。
謝謝!
假設您已在服務容器中定義了緩存機制,則可以執行以下操作:
public function getRobotsParts($parameters=null)
{
$di = \Phalcon\DI::getDefault();
$key = 'cache_robots_parts_' . $this->id;
$cache = $di->cache->get($key);
if (null == $cache) {
$results = $this->getRelated('RobotsParts', $parameters);
} else {
$results = $cache;
}
return $results;
}
它可能寫得很簡短:
public function getRobotsParts($parameters=null)
{
$parameters['cache'] = array(
'lifetime' => 123,
'key' => 'cache_robots_parts_' . $this->id,
);
return $this->getRelated('RobotsParts', $parameters);
}
或更短,如果在方法中設置了$parameters['cache']
,則導致
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.