PhalconMvcModels - 模型关系和缓存


PhalconMvcModels - 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']方法中设置,这导致了这种情况