【问题标题】:Symfony2 Get just 1 row of oneToMany EntitySymfony2 仅获取 1 行 oneToMany 实体
【发布时间】:2014-08-25 05:06:01
【问题描述】:

我有一个用户实体和一个日志实体。我有一个从用户到日志的 OneToMany 连接。 在我的日志表中存储了根据用户的日志条目。

我输出一个用户列表:

控制器:

$user = $this->getDoctrine()
        ->getRepository('SeotoolMainBundle:User')
        ->findBy(array('isActive' => 1, 'isAdmin' => 0));

树枝

{% for user in list_user %}
    {{ user.username }}
{% endfor %}

现在我想接收日志表的一行,按名为“日期”的字段排序,并在 for user 循环中返回,如下所示:

{% for user in list_user %}
    {{ user.username }}
    {{ user.log.lastEntry
{% endfor %}

我该怎么做?

实体 User.php:

/**
 * @ORM\OneToMany(targetEntity="Log", mappedBy="user")
 * @ORM\OneToMany(targetEntity="Log", mappedBy="editor")
 */
protected $log;

实体日志.php

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="log")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
protected $User;

【问题讨论】:

    标签: php entity-framework symfony


    【解决方案1】:

    假设您访问LogCollection 对象的getter 是getLogMessages 方法,并假设您可以使用getMessage 方法访问日志消息,以下应该可以解决它:

    {{ User.getLogMessages().last().getMessage() }}
    

    last 方法使您可以访问集合中存储的最后一个元素。

    顺便说一下,你应该使用OrderBy annotation,否则订单必须被认为是未定义的。 (尽管实际上,您通常会按照插入的顺序获取元素)。

    【讨论】:

    • 我的“日志消息”字段名为“log_title”。所以应该是 {{ user.getLogLogTitle().last().getLogTitle() }} ???有了这个我得到这个例外:对象“Proxies__CG__\Seotool\MainBundle\Entity\User”的方法“getLogLogTitle”在/Applications/MAMP/htdocs/Seotool/src/Seotool/MainBundle/Resources/views/Dashboard/taskManager中不存在.html.twig 第 29 行
    • 您的User 对象必须有一个获取日志条目的方法。此 getter 返回一个 ArrayCollectionDoctrineCollection 对象。他们都有各种方法来获取集合的值,例如getValues() 获取所有元素,或 first() 获取第一个元素,或 last() 获取最后一个元素。
    • 好吧,所以我需要更新我的 getLog 方法。谢谢,我会努力的:-)
    • 表示 OneToMany 关系的每个类属性都应将属性的值设置为空 ArrayCollection。 (app/console doctrine:generate:entities YourFoobarBundle 会为你做这件事,否则,如果你已经有一个类的构造函数,插入$this->myOneToManyCollection = new \Doctrine\Common\Collections\ArrayCollection();)。 getter/setter 不需要包含任何特殊的东西,它们也像所有其他的一样工作。
    【解决方案2】:

    我现在在 TWIG 中解决了它。但这一点都不好……我更喜欢控制器内部的解决方案,而不是 VIEW 中的解决方案。

    {% for log in last_userlog|reverse if(log.user.Id == user.Id) %}
        {% if loop.index == 1 %}
            {{ log.logTitle }}
        {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2015-02-03
      相关资源
      最近更新 更多