title: Doctrine 2 - (sometimes) duplicate related entities on flush
body: <p>I have php worker which is executed every 60 sec. The worker go thru articles and publish them.</p>
  
  <p>I have repository:</p>
  
  <pre><code>public function findAllUnpublished()
  {
      $query = $this-&gt;entityManager-&gt;createQuery('SELECT i FROM Extra\Item\Item i
              WHERE i.status = :status')
              -&gt;setParameter('status', ItemStatusEnum::UNPUBLISHED);
      return $query-&gt;getResult();
  }
  </code></pre>
  
  <p>and facade</p>
  
  <pre><code>public function publishUnpublished()
  {
      $items = $this-&gt;cliRepository-&gt;findAllUnpublished();
      foreach ($items as $item) {
          $item-&gt;setPublish(TRUE);
          $this-&gt;entityManager-&gt;persist($item);
      }
      $this-&gt;entityManager-&gt;flush();
      $this-&gt;itemChangedObserver-&gt;notifyBatchPublished($items); // this clear cache on web server
      return $items;
  }
  </code></pre>
  
  <p>and the worker where is called the facade</p>
  
  <pre><code>public function execute()
  {
      $this-&gt;logger-&gt;logMessage(ILogger::DEBUG, 'Start publising');
  
      $items = $this-&gt;itemFacade-&gt;publishUnpublished();
      $itemsIds = array_map(function ($item) {
          return $item-&gt;getId();
      }, $items);
      $this-&gt;logger-&gt;logMessage(
          ILogger::DEBUG,
          'Published %d items (%s)',
          count($items),
          implode(', ', $itemsIds)
      );
  
      $this-&gt;logger-&gt;logMessage(ILogger::DEBUG, 'End publising');
  
      return IJob::OK;
  }
  </code></pre>
  
  <p>Problem is that sometimes(not every turn) the worker duplicate related images in gallery.</p>
  
  <p>Article:</p>
  
  <pre><code>/**
   * @var \Doctrine\Common\Collections\Collection
   *
   * @OneToMany(targetEntity="gallery", mappedBy="article", cascade={"persist", "remove"})
   * @OrderBy({"position" = "ASC"})
   *
   */
  private $gallery;
  </code></pre>
  
  <p>Gallery:</p>
  
  <pre><code>/**
   * @var \Article
   *
   * @ManyToOne(targetEntity="Article", inversedBy="gallery")
   */
  private $article;
  </code></pre>
  
  <p>Has it ever happened to someone?</p>