Reputation: 157
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;
Upvotes: 0
Views: 562
Reputation: 13107
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).
Upvotes: 1
Reputation: 157
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 %}
Upvotes: 0