【问题标题】:Twig & PHP ActiveRecord - Cannot access field from join tableTwig & PHP ActiveRecord - 无法从连接表访问字段
【发布时间】:2012-05-22 12:16:46
【问题描述】:

我无法使用 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);

template.twig

{% 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 是否为数组并且 bar 是否为有效元素;如果没有,返回一个 空值。

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

【问题讨论】:

标签: php codeigniter twig phpactiverecord


【解决方案1】:

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

/**
 * 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-28
    • 2010-12-31
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多