I have a People class and a Group class. I know what group each man is part of through its 'group' field, but I don't know what people are in a group. To do that I have to find all people in the group by querying the People table.
Here are just the relevant parts of my classes:
class People
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(name="id",type="integer")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Bundle\Entity\Groups")
* @ORM\JoinColumn(referencedColumnName="id")
*/
protected $group;
.....
And here is part of my Group class.
class Group
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...
What I'm trying to do is count how many people are in each group and pass it in a twig template like so:
{% for group in allGroups %}
<li>name: {{group.name}} </li>
<li>date:{{ group.createdAt|date('d-m-Y H:i:s') }}</li>
<li>Number of people: {{ group.peopleNo}}</li>
<hr>
{% endfor %}
The problem is that I can't seem to find out how to calculate and pass the number of people in each group. All the other data is easy by calling the doctrine and getting the repository and passing the group object to the view, but how to pass additional data for my records?
The group.peopleNo
is not a property of my Group class. The only way for me to get it is go through the People class and count for each group how many people are in the group. But how do I pass it through the controller to the view?
Using the answer below I get this structure:
array(2) {
[0]=>
array(2) {
[0]=>
string(8) "Array(4)"
["total_peoples"]=>
string(1) "3"
}
[1]=>
array(2) {
[0]=>
string(8) "Array(4)"
["total_peoples"]=>
string(1) "1"
}
}
I'm not sure how can I loop through it in twig to display each group's number because it's indexed in order starting with 0, rather than indexed by my group id's. I think it's fine if a group has no people, then I'll just say it has 0 people if it can't find a record with it. The information is correct, I have two groups, one with 1 and other with 3 people, but their id's are 1 and 2, not 0 and 1.
Here's how my twig would look like, foreach in foreach seems like bad practice:
{% for group in groups %}
<li> {{ group .name|e }}</li>
<li>{{ group .createdAt|date('d-m-Y H:i:s') }}</li>
<li>
{% for key, ppno in peopleno %}
{% if ppno [key] is defined %}
{% if ppno [key]['id']==ticket.id %}
people: {{ peopleno [key]['total_peoples'] }}
{% endif %}
{% else %}
people:0
{% endif %}
{% endfor %}
</li>
<hr>
{% endfor %}