沃梦达 / 编程问答 / php问题 / 正文

无法访问 Twig 上的 Eloquent 属性

Cannot access Eloquent attributes on Twig(无法访问 Twig 上的 Eloquent 属性)

本文介绍了无法访问 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 属性

基础教程推荐