Php 避免自动水合
我正在使用DoctrineExtension.Tree的旧版本,但我没有buildTree。所以我也想这么做,但我一直遇到一个问题: 每次我使用findHierarchy(见下文)并对层次结构中的所有子级进行迭代时,都会得到两次。因为Doctrine仍然查询以查找子项(即使我在find Hierarchy中加载了它们),所以这里有一些有用的代码: 我的实体中的两个功能Php 避免自动水合,php,symfony,doctrine,Php,Symfony,Doctrine,我正在使用DoctrineExtension.Tree的旧版本,但我没有buildTree。所以我也想这么做,但我一直遇到一个问题: 每次我使用findHierarchy(见下文)并对层次结构中的所有子级进行迭代时,都会得到两次。因为Doctrine仍然查询以查找子项(即使我在find Hierarchy中加载了它们),所以这里有一些有用的代码: 我的实体中的两个功能 /** * Add children * * @param BGCom\MontreuxBundle\Entity\Cat
/**
* Add children
*
* @param BGCom\MontreuxBundle\Entity\Category $children
*/
public function addChildren(\BGCom\MontreuxBundle\Entity\Category $children)
{
$children->setParent($this);
$this->children[] = $children;
}
/**
* Get children
*
* @return Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
在我的回购中查找层次结构:
public function findHierarchy() {
$qb = $this
->createQueryBuilder('node')
->where('node.lvl < 2')
->andWhere('node.in_menu = 1')
->orderBy('node.root, node.lvl', 'ASC');
// set hint to translate nodes
$query = $qb->getQuery()->setHint(
Query::HINT_CUSTOM_OUTPUT_WALKER,
'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
);
$res = $query->getResult();
//Now build the right entity
// build tree in english
$i = 0;
$j = 0;
// We rebuild the tree
$parent = array();
while($i < count($res)) {
$cur = $res[$i];
$parent[] = $cur;
$i++;
while ($i < count($res) && $res[$i]->getRoot() === $cur->getId()) {
$cur->addChildren($res[$i]);
$i++;
}
}
return $parent;
}
公共函数findhierarch(){
$qb=$this
->createQueryBuilder('节点')
->其中('node.lvl<2')
->andWhere('node.in_menu=1')
->orderBy('node.root,node.lvl','ASC');
//设置转换节点的提示
$query=$qb->getQuery()->setHint(
查询::提示\u自定义\u输出\u WALKER,
“Gedmo\\translateable\\Query\\TreeWalker\\translateionwalker”
);
$res=$query->getResult();
//现在构建正确的实体
//用英语建树
$i=0;
$j=0;
//我们重建这棵树
$parent=array();
而($igetRoot()===$cur->getId()){
$cur->addChildren($res[$i]);
$i++;
}
}
返回$parent;
}
我的看法是:
{% for root in trees %}
<li>
<a href="{{ category_path(root) }}">{{ root.name }}</a>
<div class="box blue-gradient">
<ul class="lvl1">
{% for twig in root.getChildren() %}
<li><a href="{{ category_path(twig)}}">
{{ twig.name }}
</a></li>
{% endfor %}
</ul>
</div>
</li>
{% endfor %}
{%用于树中的根%}
{root.getChildren()%%中的细枝的百分比}
{%endfor%}
{%endfor%}
所以要明确的是:有没有办法避免条令质疑实体中是否已经存在一些子实体
非常感谢您的帮助Doctrine2永远不会实例化同一数据库行的两个实例 同一个对象可能有两次 通过执行以下操作,可以避免在
$children
数组中两次设置类别
:
public function addChildren(\BGCom\MontreuxBundle\Entity\Category $children)
{
$children->setParent($this);
if (!$this->children->has($children)) {
$this->children[] = $children;
}
}
即使已经加载了子项,Doctrine也会查询数据库。我想避免这种情况