У меня есть модель, где у категорий есть дети и родители. Продукты связаны с категорией. Я хотел бы получить список продуктов от детей определенной категории. Я думал о том, чтобы сделать что-то похожее на doctrine1 в моих шаблонах:
{% for category in productsByCategories %}
<h2>{{ category.label }}</h2>
<ul class="products-list">
{% for product in category.getLatestProductFromChildCategories() %}
Однако я не знаю, как это сделать, поскольку мне нужно передать объект репозитория категории в объект моей категории, и я уверен, что это не очень хорошая идея.
Как правило, как я могу запросить объект категории (аналогично тому, как мы делали записи в doctrine1)?
Благодаря !
Что-то вроде этого достигнет того, чего вы хотите?
прут
{% 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);
}
// ...
Я думаю, вы также можете попробовать запросить новейшие продукты в своем контроллере.
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;
}