【问题标题】:Symfony 4 Cannot access to mappedEntity in twigSymfony 4无法访问树枝中的mappedEntity
【发布时间】:2018-02-15 14:43:10
【问题描述】:

我有两个模型,Bodyshops 和 BodyshopsSchedule

我以这样的多对多关系相互绑定

Entity/Bodyshops.php

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="App\Entity\BodyshopsSchedule", inversedBy="bodyshops")
 * @ORM\JoinTable(name="join_bodyshops_bodyshopsSchedule")
 */
private $schedules;

实体/BodyshopsSchedule

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="App\Entity\Bodyshops", mappedBy="schedules")
 */
private $bodyshops;

我在每个文件中为每个值创建了一个添加、获取和设置函数

我将它们绑定在一起,在 phpMyAdmin 中我可以在 joinTable 中看到一切都很好!

但是当我尝试打印 BodyshopsSchedule 跨 Bodyshops 类的属性时,它不起作用并且出现错误

类“Doctrine\ORM\PersistentCollection”的 ArrayAccess 对象中的键“0”不存在。

来自

<h5 id="{{bodyshop.id ~ '_city'}}" class="card-text"> {{ bodyshop.schedules[0].day }} </h5>

我尝试使用 {{ bodyshop.schedules.day|first }}

属性 "day" 和方法 "day()"、"getday()"/"isday()"/"hasday()" 或 "__call()" 都不存在并且具有公共在“Doctrine\ORM\PersistentCollection”类中访问。

在 for 中进行迭代

Key "" 用于键为 "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18、19、20、21" 不存在。

但我总是出错

我想知道如何获取 BodyshopsSchedule 而不是 PersistentCollection。

感谢阅读;)

【问题讨论】:

    标签: php symfony doctrine twig


    【解决方案1】:

    你应该使用:

    {{ bodyshop.schedules.first.day }}
    

    由于schedules 是实现Collection interface 的类的对象,您可以在Twig 中使用its methods。您还应该阅读如何在 Twig 中handle collections

    【讨论】:

    • 我也已经尝试过了,我得到一个“无法访问布尔变量 ("") 上的属性 ("day")。我认为这是像其他人一样的错误,但没有!这是个好方法,我想我明白了,因为我的一天是 varchar(1) 你知道我该如何纠正它吗?
    • 当我得到带有键“0、1、2、3、4、5、 6、7、8、9、10、11、12、13、14、15、16、17、18、19、20、21" 不存在。"这就是为什么我认为我也有索引问题
    • 我也可以使用 {{ bodyshop.schedules.get(0).day }} !但是我尝试获取的参数可能为空,并且 {% if bodyshop.schedules 已定义 %} 没有更正任何东西:(
    • {{ bodyshop.schedules.get(0).Value|default('undefined') }} 工作!谢谢你的帮助!
    • 先阅读合约(接口详情)。它表示如果未找到元素,则第一个方法返回 Boolean false。
    猜你喜欢
    • 2016-02-29
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多