title: How to persist only one end of a relationship and the other one only if the entity doesn't exist?
body: <p>I have a complex/nested object created by automatic hydration from <code>Zend\Form</code> data. Now I want to save it with Doctrine 2. The best case would be just one <code>persist(...)</code> and one <code>flush(...)</code> call on the top level. But it doesn't work like this. So now I have following problem:</p>
  <p>There are objects <code>User</code> and <code>Order</code>. The relationship is <code>1:n</code> (so, <code>1</code> <code>User</code> has <code>n</code> <code>Order</code>s). The <code>User</code> exists already. When a <code>User</code> <code>Joe</code> tries to save more than one <code>Order</code> (e.g. its second order), an error occurs:</p>
  <blockquote>
  <p>A new entity was found through the relationship '...\Order#user' that was not configured to cascade persist operations for entity: ...\User@000000003ba4559d000000005be8d831. 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;}). If you cannot find out which entity causes the problem implement '...\User#__toString()' to get a clue.</p>
  </blockquote>
  <p>Allright, I add <code>cascade={&quot;persist&quot;}</code> (though it doesn't make sense here, but anyway, just to try it out):</p>
  <pre><code>class Order
  {
      ...
      /**
       * @var User
       *
       * @ORM\ManyToOne(targetEntity=&quot;User&quot;, cascade={&quot;persist&quot;})
       */
      protected $user;
      ...
  }
  </code></pre>
  <p>Now it works, if the given <code>User</code> doesn't exist: An <code>Order</code> and a <code>User</code> is created.</p>
  <p>But if the <code>User</code> exists, an error occurs:</p>
  <blockquote>
  <p>An exception occurred while executing 'INSERT INTO user (username, role, created, updated) VALUES (?, ?, ?, ?)' with params [&quot;myusername&quot;, &quot;member&quot;, null, null]:</p>
  <p>SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'myusername' for key 'username_UNIQUE'</p>
  </blockquote>
  <p><strong>How to handle the saving so, that the <code>User</code> only gets saved, if it doesn't exist yet?</strong></p>