Would something like this achieve what you want ?
Twig
{% for category in productsByCategories %}
<h2>{{ category.label }}</h2>
<ul class="products-list">
{# Loop through child categories #}
{% for child in category.children %}
{# Get products from the current child category #}
{% for product in child.latestProducts %}
<li>{{ product }}</li>
{% endfor %}
{% endfor %}
{% endfor %}
Category.php
<?php
// ...
public function latestProducts() {
$length = 10;
if ($this->products->count() < $length) $length = $this->products->count();
$offset = $this->products->count() - $length;
return $this->products->slice($offset, $length);
}
// ...
I guess you could also try querying the latest products in your controller.
Controller.php
<?php
public function showAction() {
// ...
$em = $this->getDoctrine()->getManager();
// Get the main categories, then loop through them
foreach ($categories as $category) {
$childrenIds = array();
foreach ($categories->getChildren() as $child) {
array_push($childrenIds, $child->getId());
}
// Get the latest products using DQL
$products = $em->createQuery('SELECT p FROM Application\ProductBundle\Entity\Product p WHERE p.category_id IN (?1) ORDER BY date_add DESC')
->setParameter(1, $childrenIds)
->setMaxResults(10);
$category->setLatestProducts($products);
}
// ...
return $this->render($template, array(
'productsByCategories' => $categories
));
}
Category.php
<?php
protected $latestProducts;
public function getLatestProducts() {
return $this->latestProducts;
}