I have a Doctrine query as follows…
$qb = $this->createQueryBuilder('s')
->select('s, csr, c')
->Join('s.classesreference', 'csr')
->Join('csr.Class', 'c')
->where('c.id = :id and csr.SpellLevel = :level')
->setParameter('level', $level)
->setParameter('id', $Class->getId())
->orderBy('s.Name','ASC')
->orderBy('csr.SpellLevel')
->getQuery();
In my Twig template I’d like to display the results of this query in a nested unordered list.
<ul>
<li>Level 0
<ul>
<!-- Level zero spells here -->
</ul>
</li>
<li>Level 1
<ul>
<!-- Level one spells here -->
</ul>
</li>
<li>Level 2
<ul>
<!-- Level two spells here -->
</ul>
</li>
<li>Level 3
<ul>
<!-- Level three spells here -->
</ul>
</li>
</ul>
I just can’t figure out how to do this in twig from the returned result set (essentially an array of Spell objects)
classesreference is a reference table between Spell and CharacterClass that also contains a field for the spell level when used by the referenced CharacterClass record.
Any help is appreciated.
Ok, after the misunderstanding of groupBy is fixed, let’s dive into this one 😉
First, what you want to achieve is a two-dimensional array like this:
The first array would contain every spell level and an array of spells.
This cannot be done with MySQL alone. MySQL returns rows, so there is no way to write a query which will give you the perfect array. So, what you want to do is write a query which gives you back all spells with their level. As I cannot fully grasp your table design, the following needs some work, but it might get you an idea:
As you can see, a foreach is used to iterate over each row (which is one spell) and add the spell to the inner array corresponding to the level. As said, you might need to change some stuff (like the spelllevel and what you store inside the array), but the overall idea should be clear.