Flush entities one by one after ObjectManager:merge()
<p>I have a Doctrine\ORM entity, consisting of new and existing database entities, created from Doctrine ObjectManager:merge(). Before flushing, I want to prevent duplicates (the context is an api where users could send e.g. duplicate city names within the same request).</p>

<p>As mentioned <a href="https://github.com/doctrine/doctrine2/issues/5092#issuecomment-181019136" rel="nofollow">in this github issue</a> it is recommended to flush after every persist() operation to be able to query my database for existing records including the ones persisted in this request. How could I do that? </p>

<p>My code is:</p>

<pre><code>...
$object = $mapper-&gt;map($objectRaw, new $modelClassName());
$object = $em-&gt;merge($object);
# I need to intervene here I suppose
$em-&gt;flush();
</code></pre>

<p>I tried:</p>

<ul>
<li>the hint mentioned on the github issue that dql would trigger a flush automatically, but after merge() that would imho mean that all new entites would be flushed, which I do not want before having checked for duplicates</li>
<li>lots of Lifecycle Events combinations, but I think that is not the way, the relevant ones already happened in the merge</li>
</ul>

<p>It seems that I need a way to flush each entity one by one and do my checks at that time, something like:</p>

<ol>
<li>Store scheduled insertions from UnitOfWork.</li>
<li>Clear list of scheduled insertions.</li>
<li>Persist and flush every insertion one by one and do my checks.</li>
</ol>

<p>Or another idea - thank you very much!</p>

<p><strong>Edit:</strong> Another idea would probably be to simply do my checks and manipulations on the object <em>before</em> <code>$em-&gt;merge($object);</code>. But you would loose the possibility of matching against repositories. So still, the question keeps me busy...</p>