Symfony doctrine: restore all parents by tree structure in one query

In my project, I have several objects that take a tree structure. On some objects I have implemented doctrine nested sets behavior and I have a clear parent-child structure. On others, I have defined my self-consistency as I have additional fields in many tables. For example:

The entity recipe has $ subrecipes SubRecipe is a new object with a parameter named weight. SubRecipe $ parentRecipe is the parent recipe. SubRecipe $ subRecipe is a child Recipe:

/**
 * @ORM\OneToOne(targetEntity="\AppBundle\Entity\FoodAnalytics\Recipe", inversedBy="parentRecipe")
 * @ORM\JoinColumn(name="subrecipeId", referencedColumnName="id", nullable=false)
 */
private $subRecipe;

/**
 * @ORM\ManyToOne(targetEntity="\AppBundle\Entity\FoodAnalytics\Recipe", inversedBy="subrecipes")
 * @ORM\JoinColumn(name="parentRecipeId", referencedColumnName="id", nullable=false, onDelete="cascade")
 */
private $parentRecipe;

      

To get the weight of a recipe, I repeat the recipes for a loop, but I query the database every time.

So far I have:

    foreach($this->getSubrecipes() as $subrecipe)
    {
        /**
         * @var $subrecipe RecipeSubrecipe
         */
        $weight += $subrecipe->getSubRecipe()->getWeight();
    }

      

How can I prevent this and return the wole tree in one request? I know I can do it myself, but how do I do this as many times as necessary to get a full tree?

    $result = $this
        ->createQueryBuilder('r')
        ->leftJoin('r.subrecipes', 's')
        ->leftJoin('s.subrecipe', 's1')
        ->leftJoin('s1.subrecipes', 's2')
        ->leftJoin('s2.subrecipe', 's3')
        ->...
    ;

      

+3


source to share





All Articles