Twig & PHP ActiveRecord - 无法访问连接表中的字段


Twig & PHP ActiveRecord - Cannot access field from join table

我无法使用 PHPActiveRecord/Twig 访问连接的表。这是简化的代码。它有两个模型(代码和用户(,每个代码属于一个用户,所以我想列出代码作者的名字。

.php

// model
class Code extends ActiveRecord'Model {
    static $belongs_to = array(
        array('user'),
    );
}
class User extends ActiveRecord'Model {
    static $has_many = array(
        array('code'),
    );
}

// controller
$codes = Code::all(array('include' => 'user'));
var_dump($codes);      //-> successfully displayed codes list and their authors
$this->twig->display('codelist.twig', $codes);

模板.树枝

{% for code in codes %}
{{ code.name }}        //-> successfully displayed code's name
{{ code.user.name }}   //-> failed to output user's name with error
{% endfor %}
// error:
// An exception has been thrown during the rendering of a template ("Call to undefined method: user") in "inc/template.twig" at line **.

我看到了这个页面:http://twig.sensiolabs.org/doc/templates.html

实现

为了方便起见,foo.bar 在PHP上做了以下事情层:

检查 foo 是否是数组并 bar 为有效元素;如果不是,如果 foo是一个对象,检查 bar 是否为有效属性;如果不是,如果 foo是一个对象,请检查 bar 是否为有效方法(即使 bar 是构造函数 - 改用 __construct(( (;如果不是,如果 foo 是对象,检查 getBar 是否为有效方法;如果不是,如果 foo 是对象,检查 isBar 是否为有效方法;如果不是,则返回 null价值。另一方面,foo['bar'] 仅适用于 PHP 数组:

检查 foo 是否是一个数组,并禁止一个有效的元素;如果不是,则返回一个空值。

虽然我可以通过 $codes[0]->user 访问用户属性,但为什么我无法访问 twig 模板文件中的用户属性?

多亏了greut,我解决了这个问题。我替换了 lib/Model 中的函数__isset.php 在 PHPActiveRecord 中。

/**
 * Determines if an attribute exists for this {@link Model}.
 *
 * @param string $attribute_name
 * @return boolean
 */
public function __isset($name)
    {
        // check for getter
        if (method_exists($this, "get_$name"))
        {
            $name = "get_$name";
            $value = $this->$name();
            return $value;
        }
        return $this->read_attribute($name);
    }

https://github.com/kla/php-activerecord/issues/156