的Symfony /嫩枝 - 递归下降的数据库查询
我在树枝模板我的类别树:的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
子类别。我假设您目前正在做这样的事情来检索您的categories
:
public function getCategories()
{
return $this->getEntityManager()->createQueryBuilder()
->select("category")
->from("App:Category", "category")
->where("category.parent IS NULL")
->getQuery()->getResult();
}
所以,如果你现在遍历数组类,并试图访问children
财产,子查询将为每个发射导致这种大量数据库查询的孩子。
相反,你应该JOIN
他们是这样的:
public function getCategories()
{
return $this->getEntityManager()->createQueryBuilder()
->select("category", "subcat")
->from("App:Category", "category")
->leftJoin("category.children", "subcat")
->where("category.parent IS NULL")
->getQuery()->getResult();
}
如果你现在遍历您categories
并访问children
财产,没有多余的查询将被解雇了!
使用上面的查询,这个片段在树枝将导致只在一个数据库查询:
{% for category in categories %}
<p>cat={{ category.id }}</p>
{% for subcat in category.children %}
<p>subcat={{ subcat.id }}</p>
{% endfor %}
<hr>
{% endfor %}
嗨,谢谢,试过你的解决方案并获得相同数量的查询。也许我应该把它取到一个json和缓存中。 – user8810516
你可以这样做,但这并不能真正解决问题。你可以请你的代码发布你的'类别'检索吗?使用我上面的代码可以很好地使用新的symfony安装。 'leftJoin'是重要的方法! – baris1892
通常,如果你的数据库查询的量取决于所获取的数据(更多数据=更多的查询),你应该考虑使用JOIN语句来减少数据库查询。如果您可以提供您的学说实体的一些代码将会很有帮助。 – baris1892
@ radon66嗨,感谢您的回复。更新我的问题。所以你认为每天一次在json中生成类别会更好,缓存并在网站上使用? – user8810516