【问题标题】:How to access linked bean fields with RedBean and Twig?如何使用 RedBean 和 Twig 访问链接的 bean 字段?
【发布时间】:2016-12-15 21:30:36
【问题描述】:

我有一个 bean (foo) 链接到另一个 bean (bar) 并且想要访问 Twig 中其他 bean (bar) 的字段。首先,我如何设置 bean 的示例

$f = R::dispense('foo');
$f->name = 'foo';

$b = R::dipsense('bar');
$b->val = 10;
R::store($b);

$f->bar = $b;
R::store($f);

我知道这里没有问题,因为所有数据库都已正确更新。现在,使用树枝:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Value</th>
        </tr>
    </thead>
    <tbody>
        {% for f in siteinfo.foos %}
            <tr>
                <td>{{f.name}}</td>
                <td>{{f.bar.val}}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

我确信几乎一切正常,因为我得到了一个正确打印名称的表格,但是没有打印任何“条形”值。 siteinfo.foos 返回R::findAll('foo', 'order by name');

任何帮助将不胜感激!

【问题讨论】:

  • Redbean 与延迟加载一起工作,首先,您需要知道 twig 中的这个 var 是 bean 还是 stdClass 或数组,您可以检查此打印 bean {{bean|var_dump}}
  • 它崩溃了,因为var_dump 是一个未知的过滤器。
  • 它似乎是作为数组加载的。在 for 循环中打印 &lt;p&gt;f&lt;/p&gt; 给出: {"id":"14","name":"foo","bar_id":"1"}
  • 有没有办法从树枝中R::load('bar', $bar_id)
  • 如果你扩展 Twig,否则R 将不被 Twig 所知

标签: php twig redbean


【解决方案1】:

解决方法:

<table>
<thead><tr><th>Name</th><th>Value</th></tr></thead>
<tbody>
    {% for f in siteinfo.foos %}
        <tr>
            <td>{{f.name}}</td>
            <td>{{f.__get('bar').val}}</td>
        </tr>
    {% endfor %}
</tbody>
</table>

__get() 的使用会强制 RedBean 库对属性进行评估。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2012-05-07
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多