Cannot access Eloquent attributes on Twig(无法访问 Twig 上的 Eloquent 属性)
问题描述
我尝试在 Slim 中使用 Twig 访问 Eloquent 属性,但出现错误.
I am trying to access an Eloquent attribute with Twig in Slim, and getting an error.
我有一个Field和一个Type对象,关系如下
I have a Field and a Type object, and the relationship is as follows
class Field extends IlluminateDatabaseEloquentModel {
protected $table = 'fields';
public function type()
{
return $this->belongsTo('modelsType');
}
当做 {{ f }}
(作为 f 一个字段)时,输出是这样的:
When doing {{ f }}
(being f a field), the output is this:
{"field_id":"1","field_name":"Your name","form_id":"2","type_id":"1","placeholder":"Please give us your name"}
而在做{{ f.type }}
的时候,结果是:
And when doing {{ f.type }}
, the result is:
消息:在第 97 行的pages/editform.html"中呈现模板期间引发了异常(类 IlluminateDatabaseEloquentRelationsBelongsTo 的对象无法转换为字符串").
Message: An exception has been thrown during the rendering of a template ("Object of class IlluminateDatabaseEloquentRelationsBelongsTo could not be converted to string") in "pages/editform.html" at line 97.
如果我尝试执行 {{ f.type.name }}
,不会抛出异常但也不会打印任何内容.
If I try to do {{ f.type.name }}
, doesn't throw up an exception but doesn't print anything either.
如果我用 PHP 来做
If I do it in PHP
$fields = $form->fields;
var_dump($fields[0]->type->name);
正确输出值.
有什么想法吗?谢谢
推荐答案
我遇到了同样的问题,偶然发现了这个问题.自己解决后,我想我会尽力帮助你.
I had the same issue and stumbled upon this question. After solving it myself, I thought I'd try to help you out.
尝试对模型进行 Eager Load:
Try doing a Eager Load on the model:
Field::with('type')->get()
这应该允许您在没有其他问题的情况下执行以下操作.
This should allow you to do the following with no other issues.
{{ f.type }}
在此处查看更多信息:http://laravel.com/docs/4.2/eloquent#eager-loading
这篇关于无法访问 Twig 上的 Eloquent 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法访问 Twig 上的 Eloquent 属性
- 从 PHP 中的输入表单获取日期 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01