Symfony2 Deep列表类别

时间:2014-04-04 22:44:47

标签: symfony doctrine-orm

您好我的电子商务类别存在一个问题。首先,我将显示我的数据库表

+----+----------+------------------+--------+
| ID | Parent   |      Name        | Status |
+----+----- ----+------------------+--------+
| 1  |          | Clothing         |   1    |
| 2  |   1      | Women            |   1    |
| 3  |   1      | Man              |   1    |
| 4  |   1      | Boys             |   1    |
| 5  |   1      | Girls            |   1    |
| 6  |   2      | Sub of Women     |   1    |
| 7  |   2      | Wub of Women     |   1    |
+----+----------+------------------+--------+

让我们解释一下: 根类别为 #ID = 1 并且 NULL 值所有子类别都具有父#ID。 每个子类别都有自己的根类别,并由ROOT类别ID标识。我在菜单中成功获取了这些数据。

enter image description here

我的存储库方法是获取父级 IS NULL

的所有类别
  public function getAllRootCategories()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT c FROM ISLabECommerceBundle:Category c WHERE c.parent IS NULL ORDER BY c.name ASC'
            )
            ->getResult();
    }

Contontroller:

   public function categoryListAction()
    {
        $em = $this->container->get('doctrine');
        $categories = $em->getRepository('ISLabECommerceBundle:Category')->getAllRootCategories();

        return $this->container->get('templating')->renderResponse(
          'ISLabECommerceBundle:Category:list.html.twig', array(
                'categories' => $categories
            )
        );
    }

嫩枝:

<ul>
{% for category in categories %}
      <li> <a href=""> {{ category.name }} </a>
        {% for sub_category in category.children %}
              <li> <a href="">{{ sub_category.name }}</a></li>
         {% endfor %}
      </li>
</ul>
{% endfor %}
</ul>

有了这个树枝,我只能获得1级深度bcs,我的存储库获取父级为空值的所有类别。

如果我想在该类别下拥有自己的类别该怎么办。

示例

Women   
  -- Sub of women   
   --- Sub of women 2

使用此存储库方法,我只能获得ROOT类别和1级子类别。 3,4,5,6级怎么样?怎么做? Bcs任何子类别都可以拥有自己的子子类别。

任何人都可以举例说明我该怎么做。加入/左加入maybie?

1 个答案:

答案 0 :(得分:2)

您可以通过将twig模板更改为递归宏来解决您的问题:

{% macro recursiveCategory(category) %}
<li>
  <a href="">{{ category.name }}</a>
  {% if category.children|length %}
  <ul>
    {% for child in category.children %}
      {{ _self.recursiveCategory(child) }}
    {% endfor %}
  </ul>
  {% endif %}
</li>
{% endmacro %}

{% if categories %}
<div id="categories">
  <ul>
    {% for category in categories %}
      {{ _self.recursiveCategory(category) }}
    {% endfor %}
  </ul>
</div>
{% endif %}

我还建议您更改存储库方法:

public function getCategoriesByParent(Category $parent = null)
{
    $qb = $this->createQueryBuilder('c')
        ->orderBy('c.name', 'ASC');

    if (is_null($parent)) {
        $qb->andWhere('c.parent IS NULL');
    } else {
        $qb->andWhere('c.parent = :parent')
            ->setParameter('parent', $parent->getId());
    }

    return $qb->getQuery()->getResult();
}

这样可以更好地控制您要从数据库中选择的内容。如果更改存储库方法,则需要将ControllerAction方法调用更改为:

$em->getRepository('ISLabECommerceBundle:Category')->getCategoriesByParent();