簡體   English   中英

原則避免自動補水

[英]doctrine avoid automatic hydration

我正在使用舊版本的DoctrineExtension.Tree,並且沒有buildTree。 所以我想做同樣的事情,但是我一直遇到一個問題:每次我使用findHierarchy(見下文)並遍歷層次結構中的所有子級時,都會得到兩次。 因為Doctrine仍然查詢以查找子級(即使我在“查找層次結構”中加載了它們),所以這里有一些有用的代碼:

我實體中的兩個功能

/**
 * 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;
}

我的觀點:

{% 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 %}

因此要明確:是否有一種方法可以避免學說查詢實體中是否已經存在某些子代?

非常感謝你的幫助

Doctrine2永遠不會實例化同一數據庫行的2個實例。

您可能有兩次相同的對象。

您可以這樣做,避免在$children數組中兩次設置一個Category

public function addChildren(\BGCom\MontreuxBundle\Entity\Category $children)
{
    $children->setParent($this);

    if (!$this->children->has($children)) {
        $this->children[] = $children;
    }   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM