title: Clone an entity with a ManyToMany Association
body: <p>I have two entities that have a ManyToMany bidirectional association: <code>$foo</code> and <code>$bar</code>. $foo is the owning side. They are joined by a middle table: <code>foo_bar</code>.</p>
  <p>I need to <strong>clone</strong> the <code>$foo</code> entity so that the new entity keeps all the associations with <code>$bar</code>. It should <strong>not</strong> create new <code>$bar</code> records, just duplicate the records in joining table <code>foo_bar</code>. So I'll have two <code>$foo</code> objects, both pointing to the same collection of <code>$bar</code> entities.</p>
  <p>How should this be handled?</p>
  <h2>$foo object:</h2>
  <pre><code>/*
   * @ORM\ManyToMany(targetEntity=&quot;Sitetheory\CoreBundle\Entity\Bar&quot;, inversedBy=&quot;foos&quot;, cascade={&quot;detach&quot;})
   * @ORM\JoinTable(name=&quot;foo_bar&quot;)
   */
  protected $bars;
  </code></pre>
  <h2>$bar object:</h2>
  <pre><code>/*
   * @ORM\ManyToMany(targetEntity=&quot;Sitetheory\CoreBundle\Entity\Foo&quot;, mappedBy=&quot;bars&quot;)
  
   */
  protected $foos;
  </code></pre>
  <h2>Failed Attempts</h2>
  <p>I've tried making <code>$foo cascade={&quot;**persist**&quot;, &quot;detach&quot;}</code> but that doesn't work: it tries to create NEW <code>$bar</code> objects which is not what we want.</p>
  <p>I've tried to re-associate the relationships (thinking the new object hashes would trigger a new persist) but that doesn't work either. On the <code>$foo</code> <code>__clone()</code> function:</p>
  <pre><code>public function __clone() {
      $bars = $this-&gt;getBars();
      if (!empty($bars)) {
          $this-&gt;setBars(new ArrayCollection());
          foreach ($bars AS $bar) {
              $this-&gt;addBar($bar);
          }
      }
  }
  </code></pre>
  <p>That just gives the error:</p>
  <blockquote>
  <p>A new entity was found through the relationship
  'Sitetheory\CoreBundle\Entity\Foo#bars' that was not configured to
  cascade persist operations for entity: Woo. To solve this issue:
  Either explicitly call EntityManager#persist() on this unknown entity
  or configure cascade persist this association in the mapping for
  example @ManyToOne(..,cascade={&quot;persist&quot;}).</p>
  </blockquote>
  <p>But if I do add persist on the entity, it gives a different error about inserting a new Bar, which of course I don't want it to do anyway.</p>
  <h1>UPDATE</h1>
  <p>Evidently, the problem was that there should not have been a <code>cascade={&quot;detach&quot;}</code>. When I removed that, the cloning worked automatically.</p>