简体   繁体   中英

Symfony2 Get just 1 row of oneToMany Entity

I have a user entity and a log entity. I have a OneToMany connection from User to Log. In my Log Table are stored log entries according to users.

I output a User list:

Controller:

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

TWIG

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

Now I want to recieve ONE row of the log table, sorted by a field called "date" and return it in the for user loop like this:

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

How do I do this?

Entity User.php:

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

Entity Log.php

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

Assuming that your getter for accessing the Log Collection object is a getLogMessages method, and assuming you can access the log message with a getMessage method, the following should solve it:

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

The last method gives you access to the last element stored in the collection.

By the way, you should use the OrderBy annotation , otherwise the order must be considered undefined. (Although, in reality, you will usually get the elements in the order they were inserted).

I solved it now in TWIG. But this isn't nice at all... I would prefere a solution inside of the controller and not in the VIEW.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM