title: Persisting multiple new associated objects in a self-referenced table with Doctrine2 and Symfony2
body: <p>I'm quite new to Doctrine2 which I'm currently using in a Symfony2 project.
  I'm trying to persist entities with a self-referencing foreign key such as the category example of the Doctrine documentation (http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#one-to-many-self-referencing). There is probably a very easy solution to this but I just couldn't find it anywhere on the web.</p>
  
  <p>For some reason, the value for the parent_id is not automatically stored by Doctrine (it's null), although I can access the id value of the object I am assigning as a parent.
  Some code will probably be straightforward. Here's the relevant part : </p>
  
  <p>The entity definition :</p>
  
  <pre><code>class Area
  {
       // id, name, type, etc...
  
      /**
       * @ORM\ManyToOne(targetEntity="Area", inversedBy="sub_areas", cascade={"persist"})
       * @ORM\JoinColumn(name="parent_area_id", referencedColumnName="id")
       */
      private $parent_area;
  
      /**
       * @ORM\OneToMany(targetEntity="Area", mappedBy="parent_area", cascade={"persist"})
       */
      private $sub_areas;
  
      /**
       * Set parent area
       *
       * @param obj $area
       */
      public function setParentArea(Area $area)
      {
          $this-&gt;aera = $area;
      }
  
      // Other getters and setters, etc.
  }
  </code></pre>
  
  <p>In the action :</p>
  
  <pre><code>$results = array();
  
  foreach($area_types as $key =&gt; $type) {
      $area = new Area();
      $area-&gt;setType($type);
      $area-&gt;setName($location-&gt;getAddressComponent($type));
  
      if(isset($parent_area)) {
          $area-&gt;setParentArea($parent_area);
      }
  
      $this-&gt;em-&gt;persist($area);
      $parent_area = $area;
      $results[] = $area-&gt;getId();
  }
  
  $this-&gt;em-&gt;flush(); 
  </code></pre>
  
  <p>The results array will output the assigned ids in Twig. I also tried using :</p>
  
  <pre><code> $area-&gt;setParentAreaId($parent_area-&gt;getId());
  </code></pre>
  
  <p>Could anyone explain how Doctrine manages the database persistence sequence of self-referenced objects ?</p>