我在树枝模板我的类别树:的Symfony /嫩枝 - 递归下降的数据库查询
{% for category in categories %}
<li>
<div class="li"><a href="{{ path('accessories_list', { 'category' : category.url }) }}">{{ category.name|trans({}, 'categories')|raw }}</a></div>
{% if category.children is not empty %}
<ul>
{% include "default/_menu_links.html.twig" with {'categories':category.children} only %}
</ul>
{% endif %}
</li>
{% endfor %}
它创建+ - 53个数据库查询,如果我有6类,并在每个单一类别7小类。
有没有办法减少这个数字? 我在doctrine中使用useResultCache(true),但看起来它不是从缓存中加载(至少不是在开发模式下)。
你如何处理类别树?
UPDATE: 实体:
...
/**
* One Category has Many Subcategories.
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent", cascade={"persist"}))
*/
private $children;
/**
* Many Subcategories have One Category.
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children", cascade={"persist"})
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
...
/**
* Add child
*
* @param \App\Entity\Product\Category $child
*
* @return Category
*/
public function addChild(\App\Entity\Product\Category $child): Category
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* @param \App\Entity\Product\Category $child
*/
public function removeChild(\App\Entity\Product\Category $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getChildren(): Collection
{
return $this->children;
}
/**
* Set parent
*
* @param \App\Entity\Product\Category $parent
*
* @return Category
*/
public function setParent(\App\Entity\Product\Category $parent = null): Category
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* @return \App\Entity\Product\Category
*/
public function getParent()
{
return $this->parent;
}
...
通常,如果你的数据库查询的量取决于所获取的数据(更多数据=更多的查询),你应该考虑使用JOIN语句来减少数据库查询。如果您可以提供您的学说实体的一些代码将会很有帮助。 – baris1892
@ radon66嗨,感谢您的回复。更新我的问题。所以你认为每天一次在json中生成类别会更好,缓存并在网站上使用? – user8810516