
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>9. Working with Associations &mdash; Doctrine 2 ORM 2 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap/css/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/layout.css" type="text/css" />
    <link rel="stylesheet" href="../_static/configurationblock.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>

    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/configurationblock.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/configurationblock.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/configurationblock.js"></script>
    <script src="../_static/bootstrap/js/bootstrap.min.js"></script>

    <script type="text/javascript">
    <!--
        $(document).ready(function() {
            $("#versions").change(function() {
                var docsUrl = $(this).val();
                window.location.href = docsUrl;
            });
        });
    -->
    </script>
    <link rel="shortcut icon" href="../_static/doctrine.ico"/>
    <link rel="top" title="Doctrine 2 ORM 2 documentation" href="../index.html" />
    <link rel="next" title="10. Events" href="events.html" />
    <link rel="prev" title="8. Working with Objects" href="working-with-objects.html" />
 
<!-- RTD Extra Head -->


<script type="text/javascript" src="//media.readthedocs.org/javascript/rtd.js"></script>
<link rel="stylesheet" href="//media.readthedocs.org/css/rtd-shim.css" type="text/css" />
<!-- end RTD <extrahead> -->

  </head>
  <body>
    <div id="wrapper">
      <div id="header">
        <h1 id="h1title"></h1>
        <div id="logo">
          <a href="http://www.doctrine-project.org/">Doctrine - PHP Database Libraries</a>
        </div>
      </div>
      <div id="nav" class="cls">
        <div class="tl cls">
          <ul>
            <li><a target="_top" href="/">home</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/about">about</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/projects.html">projects</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/projects/orm">orm</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/projects/dbal">dbal</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/blog">blog</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/jira">development</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/contribute">contribute</a></li>
            <li><a class="" target="_top" href="http://www.doctrine-project.org/community">community</a></li>
          </ul>
        </div>
      </div>
      <div id="content" class="cls">
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="events.html" title="10. Events"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="working-with-objects.html" title="8. Working with Objects"
             accesskey="P">previous</a> |</li>
        <li><a href="/">Doctrine Homepage</a> &raquo;</li>
        <li><a href="../index.html">Doctrine 2 ORM 2 documentation</a> &raquo;</li> 
      </ul>
    </div>  

        <div class="document">
            <div class="documentwrapper">
                <div class="bodywrapper">

              <div class="body" >
                
  <div class="section" id="working-with-associations">
<h1>9. Working with Associations<a class="headerlink" href="#working-with-associations" title="Permalink to this headline">¶</a></h1>
<p>Associations between entities are represented just like in regular
object-oriented PHP code using references to other objects or
collections of objects.</p>
<p>Changes to associations in your code are not synchronized to the
database directly, only when calling <tt class="docutils literal"><span class="pre">EntityManager#flush()</span></tt>.</p>
<p>There are other concepts you should know about when working
with associations in Doctrine:</p>
<ul class="simple">
<li>If an entity is removed from a collection, the association is
removed, not the entity itself. A collection of entities always
only represents the association to the containing entities, not the
entity itself.</li>
<li>When a bidirectional assocation is updated, Doctrine only checks
on one of both sides for these changes. This is called the <a class="reference internal" href="unitofwork-associations.html"><em>owning side</em></a>
of the association.</li>
<li>A property with a reference to many entities has to be instances of the
<tt class="docutils literal"><span class="pre">Doctrine\Common\Collections\Collection</span></tt> interface.</li>
</ul>
<div class="section" id="association-example-entities">
<h2>9.1. Association Example Entities<a class="headerlink" href="#association-example-entities" title="Permalink to this headline">¶</a></h2>
<p>We will use a simple comment system with Users and Comments as
entities to show examples of association management. See the PHP
docblocks of each association in the following example for
information about its type and if it&#8217;s the owning or inverse side.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="sd">/** @Entity */</span>
<span class="k">class</span> <span class="nc">User</span>
<span class="p">{</span>
    <span class="sd">/** @Id @GeneratedValue @Column(type=&quot;string&quot;) */</span>
    <span class="k">private</span> <span class="nv">$id</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Bidirectional - Many users have Many favorite comments (OWNING SIDE)</span>
<span class="sd">     *</span>
<span class="sd">     * @ManyToMany(targetEntity=&quot;Comment&quot;, inversedBy=&quot;userFavorites&quot;)</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$favorites</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Unidirectional - Many users have marked many comments as read</span>
<span class="sd">     *</span>
<span class="sd">     * @ManyToMany(targetEntity=&quot;Comment&quot;)</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$commentsRead</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Bidirectional - One-To-Many (INVERSE SIDE)</span>
<span class="sd">     *</span>
<span class="sd">     * @OneToMany(targetEntity=&quot;Comment&quot;, mappedBy=&quot;author&quot;)</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$commentsAuthored</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Unidirectional - Many-To-One</span>
<span class="sd">     *</span>
<span class="sd">     * @ManyToOne(targetEntity=&quot;Comment&quot;)</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$firstComment</span><span class="p">;</span>
<span class="p">}</span>

<span class="sd">/** @Entity */</span>
<span class="k">class</span> <span class="nc">Comment</span>
<span class="p">{</span>
    <span class="sd">/** @Id @GeneratedValue @Column(type=&quot;string&quot;) */</span>
    <span class="k">private</span> <span class="nv">$id</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Bidirectional - Many comments are favorited by many users (INVERSE SIDE)</span>
<span class="sd">     *</span>
<span class="sd">     * @ManyToMany(targetEntity=&quot;User&quot;, mappedBy=&quot;favorites&quot;)</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$userFavorites</span><span class="p">;</span>

    <span class="sd">/**</span>
<span class="sd">     * Bidirectional - Many Comments are authored by one user (OWNING SIDE)</span>
<span class="sd">     *</span>
<span class="sd">     * @ManyToOne(targetEntity=&quot;User&quot;, inversedBy=&quot;commentsAuthored&quot;)</span>
<span class="sd">     */</span>
     <span class="k">private</span> <span class="nv">$author</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This two entities generate the following MySQL Schema (Foreign Key
definitions omitted):</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="k">User</span> <span class="p">(</span>
    <span class="n">id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">firstComment_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">DEFAULT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">id</span><span class="p">)</span>
<span class="p">)</span> <span class="n">ENGINE</span> <span class="o">=</span> <span class="n">InnoDB</span><span class="p">;</span>

<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="k">Comment</span> <span class="p">(</span>
    <span class="n">id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">author_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">DEFAULT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">id</span><span class="p">)</span>
<span class="p">)</span> <span class="n">ENGINE</span> <span class="o">=</span> <span class="n">InnoDB</span><span class="p">;</span>

<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">user_favorite_comments</span> <span class="p">(</span>
    <span class="n">user_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">favorite_comment_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">user_id</span><span class="p">,</span> <span class="n">favorite_comment_id</span><span class="p">)</span>
<span class="p">)</span> <span class="n">ENGINE</span> <span class="o">=</span> <span class="n">InnoDB</span><span class="p">;</span>

<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">user_read_comments</span> <span class="p">(</span>
    <span class="n">user_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">comment_id</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">user_id</span><span class="p">,</span> <span class="n">comment_id</span><span class="p">)</span>
<span class="p">)</span> <span class="n">ENGINE</span> <span class="o">=</span> <span class="n">InnoDB</span><span class="p">;</span>
</pre></div>
</div>
</div>
<div class="section" id="establishing-associations">
<h2>9.2. Establishing Associations<a class="headerlink" href="#establishing-associations" title="Permalink to this headline">¶</a></h2>
<p>Establishing an association between two entities is
straight-forward. Here are some examples for the unidirectional
relations of the <tt class="docutils literal"><span class="pre">User</span></tt>:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">User</span>
<span class="p">{</span>
    <span class="c1">// ...</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getReadComments</span><span class="p">()</span> <span class="p">{</span>
         <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">commentsRead</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">setFirstComment</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$c</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">firstComment</span> <span class="o">=</span> <span class="nv">$c</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The interaction code would then look like in the following snippet
(<tt class="docutils literal"><span class="pre">$em</span></tt> here is an instance of the EntityManager):</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$user</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="s1">&#39;User&#39;</span><span class="p">,</span> <span class="nv">$userId</span><span class="p">);</span>

<span class="c1">// unidirectional many to many</span>
<span class="nv">$comment</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="s1">&#39;Comment&#39;</span><span class="p">,</span> <span class="nv">$readCommentId</span><span class="p">);</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getReadComments</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>

<span class="c1">// unidirectional many to one</span>
<span class="nv">$myFirstComment</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Comment</span><span class="p">();</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">setFirstComment</span><span class="p">(</span><span class="nv">$myFirstComment</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">persist</span><span class="p">(</span><span class="nv">$myFirstComment</span><span class="p">);</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>
</pre></div>
</div>
<p>In the case of bi-directional associations you have to update the
fields on both sides:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">User</span>
<span class="p">{</span>
    <span class="c1">// ..</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">getAuthoredComments</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">commentsAuthored</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">getFavoriteComments</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">favorites</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">Comment</span>
<span class="p">{</span>
    <span class="c1">// ...</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">getUserFavorites</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">userFavorites</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">setAuthor</span><span class="p">(</span><span class="nx">User</span> <span class="nv">$author</span> <span class="o">=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">author</span> <span class="o">=</span> <span class="nv">$author</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="c1">// Many-to-Many</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$favoriteComment</span><span class="p">);</span>
<span class="nv">$favoriteComment</span><span class="o">-&gt;</span><span class="na">getUserFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>

<span class="c1">// Many-To-One / One-To-Many Bidirectional</span>
<span class="nv">$newComment</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Comment</span><span class="p">();</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getAuthoredComments</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$newComment</span><span class="p">);</span>
<span class="nv">$newComment</span><span class="o">-&gt;</span><span class="na">setAuthor</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">persist</span><span class="p">(</span><span class="nv">$newComment</span><span class="p">);</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>
</pre></div>
</div>
<p>Notice how always both sides of the bidirectional association are
updated. The previous unidirectional associations were simpler to
handle.</p>
</div>
<div class="section" id="removing-associations">
<h2>9.3. Removing Associations<a class="headerlink" href="#removing-associations" title="Permalink to this headline">¶</a></h2>
<p>Removing an association between two entities is similarly
straight-forward. There are two strategies to do so, by key and by
element. Here are some examples:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="c1">// Remove by Elements</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getComments</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">removeElement</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
<span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">setAuthor</span><span class="p">(</span><span class="k">null</span><span class="p">);</span>

<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">removeElement</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
<span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">getUserFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">removeElement</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>

<span class="c1">// Remove by Key</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getComments</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">remove</span><span class="p">(</span><span class="nv">$ithComment</span><span class="p">);</span>
<span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">setAuthor</span><span class="p">(</span><span class="k">null</span><span class="p">);</span>
</pre></div>
</div>
<p>You need to call <tt class="docutils literal"><span class="pre">$em-&gt;flush()</span></tt> to make persist these changes in
the database permanently.</p>
<p>Notice how both sides of the bidirectional association are always
updated. Unidirectional associations are consequently simpler to
handle. Also note that if you use type-hinting in your methods, i.e.
<tt class="docutils literal"><span class="pre">setAddress(Address</span> <span class="pre">$address)</span></tt>, PHP will only allow null
values if <tt class="docutils literal"><span class="pre">null</span></tt> is set as default value. Otherwise
setAddress(null) will fail for removing the association. If you
insist on type-hinting a typical way to deal with this is to
provide a special method, like <tt class="docutils literal"><span class="pre">removeAddress()</span></tt>. This can also
provide better encapsulation as it hides the internal meaning of
not having an address.</p>
<p>When working with collections, keep in mind that a Collection is
essentially an ordered map (just like a PHP array). That is why the
<tt class="docutils literal"><span class="pre">remove</span></tt> operation accepts an index/key. <tt class="docutils literal"><span class="pre">removeElement</span></tt> is a
separate method that has O(n) complexity using <tt class="docutils literal"><span class="pre">array_search</span></tt>,
where n is the size of the map.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since Doctrine always only looks at the owning side of a
bidirectional association for updates, it is not necessary for
write operations that an inverse collection of a bidirectional
one-to-many or many-to-many association is updated. This knowledge
can often be used to improve performance by avoiding the loading of
the inverse collection.</p>
</div>
<p>You can also clear the contents of a whole collection using the
<tt class="docutils literal"><span class="pre">Collections::clear()</span></tt> method. You should be aware that using
this method can lead to a straight and optimized database delete or
update call during the flush operation that is not aware of
entities that have been re-added to the collection.</p>
<p>Say you clear a collection of tags by calling
<tt class="docutils literal"><span class="pre">$post-&gt;getTags()-&gt;clear();</span></tt> and then call
<tt class="docutils literal"><span class="pre">$post-&gt;getTags()-&gt;add($tag)</span></tt>. This will not recognize the tag having
already been added previously and will consequently issue two separate database
calls.</p>
</div>
<div class="section" id="association-management-methods">
<h2>9.4. Association Management Methods<a class="headerlink" href="#association-management-methods" title="Permalink to this headline">¶</a></h2>
<p>It is generally a good idea to encapsulate proper association
management inside the entity classes. This makes it easier to use
the class correctly and can encapsulate details about how the
association is maintained.</p>
<p>The following code shows updates to the previous User and Comment
example that encapsulate much of the association management code:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">User</span>
<span class="p">{</span>
    <span class="c1">//...</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">markCommentRead</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$comment</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// Collections implement ArrayAccess</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">commentsRead</span><span class="p">[]</span> <span class="o">=</span> <span class="nv">$comment</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">addComment</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$comment</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nb">count</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">commentsAuthored</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">setFirstComment</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">comments</span><span class="p">[]</span> <span class="o">=</span> <span class="nv">$comment</span><span class="p">;</span>
        <span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">setAuthor</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">function</span> <span class="nf">setFirstComment</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$c</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">firstComment</span> <span class="o">=</span> <span class="nv">$c</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">addFavorite</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$comment</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">favorites</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
        <span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">addUserFavorite</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">removeFavorite</span><span class="p">(</span><span class="nx">Comment</span> <span class="nv">$comment</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">favorites</span><span class="o">-&gt;</span><span class="na">removeElement</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
        <span class="nv">$comment</span><span class="o">-&gt;</span><span class="na">removeUserFavorite</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">Comment</span>
<span class="p">{</span>
    <span class="c1">// ..</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">addUserFavorite</span><span class="p">(</span><span class="nx">User</span> <span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">userFavorites</span><span class="p">[]</span> <span class="o">=</span> <span class="nv">$user</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">removeUserFavorite</span><span class="p">(</span><span class="nx">User</span> <span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">userFavorites</span><span class="o">-&gt;</span><span class="na">removeElement</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>You will notice that <tt class="docutils literal"><span class="pre">addUserFavorite</span></tt> and <tt class="docutils literal"><span class="pre">removeUserFavorite</span></tt>
do not call <tt class="docutils literal"><span class="pre">addFavorite</span></tt> and <tt class="docutils literal"><span class="pre">removeFavorite</span></tt>, thus the
bidirectional association is strictly-speaking still incomplete.
However if you would naively add the <tt class="docutils literal"><span class="pre">addFavorite</span></tt> in
<tt class="docutils literal"><span class="pre">addUserFavorite</span></tt>, you end up with an infinite loop, so more work
is needed. As you can see, proper bidirectional association
management in plain OOP is a non-trivial task and encapsulating all
the details inside the classes can be challenging.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you want to make sure that your collections are perfectly
encapsulated you should not return them from a
<tt class="docutils literal"><span class="pre">getCollectionName()</span></tt> method directly, but call
<tt class="docutils literal"><span class="pre">$collection-&gt;toArray()</span></tt>. This way a client programmer for the
entity cannot circumvent the logic you implement on your entity for
association management. For example:</p>
</div>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">User</span> <span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getReadComments</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">commentsRead</span><span class="o">-&gt;</span><span class="na">toArray</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This will however always initialize the collection, with all the
performance penalties given the size. In some scenarios of large
collections it might even be a good idea to completely hide the
read access behind methods on the EntityRepository.</p>
<p>There is no single, best way for association management. It greatly
depends on the requirements of your concrete domain model as well
as your preferences.</p>
</div>
<div class="section" id="synchronizing-bidirectional-collections">
<h2>9.5. Synchronizing Bidirectional Collections<a class="headerlink" href="#synchronizing-bidirectional-collections" title="Permalink to this headline">¶</a></h2>
<p>In the case of Many-To-Many associations you as the developer have the
responsibility of keeping the collections on the owning and inverse side
in sync when you apply changes to them. Doctrine can only
guarantee a consistent state for the hydration, not for your client
code.</p>
<p>Using the User-Comment entities from above, a very simple example
can show the possible caveats you can encounter:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$favoriteComment</span><span class="p">);</span>
<span class="c1">// not calling $favoriteComment-&gt;getUserFavorites()-&gt;add($user);</span>

<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">contains</span><span class="p">(</span><span class="nv">$favoriteComment</span><span class="p">);</span> <span class="c1">// TRUE</span>
<span class="nv">$favoriteComment</span><span class="o">-&gt;</span><span class="na">getUserFavorites</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">contains</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span> <span class="c1">// FALSE</span>
</pre></div>
</div>
<p>There are two approaches to handle this problem in your code:</p>
<ol class="arabic simple">
<li>Ignore updating the inverse side of bidirectional collections,
BUT never read from them in requests that changed their state. In
the next Request Doctrine hydrates the consistent collection state
again.</li>
<li>Always keep the bidirectional collections in sync through
association management methods. Reads of the Collections directly
after changes are consistent then.</li>
</ol>
</div>
<div class="section" id="transitive-persistence-cascade-operations">
<h2>9.6. Transitive persistence / Cascade Operations<a class="headerlink" href="#transitive-persistence-cascade-operations" title="Permalink to this headline">¶</a></h2>
<p>Persisting, removing, detaching and merging individual entities can
become pretty cumbersome, especially when a highly interweaved object graph
is involved. Therefore Doctrine 2 provides a
mechanism for transitive persistence through cascading of these
operations. Each association to another entity or a collection of
entities can be configured to automatically cascade certain
operations. By default, no operations are cascaded.</p>
<p>The following cascade options exist:</p>
<ul class="simple">
<li>persist : Cascades persist operations to the associated
entities.</li>
<li>remove : Cascades remove operations to the associated entities.</li>
<li>merge : Cascades merge operations to the associated entities.</li>
<li>detach : Cascades detach operations to the associated entities.</li>
<li>all : Cascades persist, remove, merge and detach operations to
associated entities.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Cascade operations are performed in memory. That means collections and related entities
are fetched into memory, even if they are still marked as lazy when
the cascade operation is about to be performed. However this approach allows
entity lifecycle events to be performed for each of these operations.</p>
<p>However, pulling objects graph into memory on cascade can cause considerable performance
overhead, especially when cascading collections are large. Makes sure
to weigh the benefits and downsides of each cascade operation that you define.</p>
<p class="last">To rely on the database level cascade operations for the delete operation instead, you can
configure each join column with the <strong>onDelete</strong> option. See the respective
mapping driver chapters for more information.</p>
</div>
<p>The following example is an extension to the User-Comment example
of this chapter. Suppose in our application a user is created
whenever he writes his first comment. In this case we would use the
following code:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$user</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">User</span><span class="p">();</span>
<span class="nv">$myFirstComment</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Comment</span><span class="p">();</span>
<span class="nv">$user</span><span class="o">-&gt;</span><span class="na">addComment</span><span class="p">(</span><span class="nv">$myFirstComment</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">persist</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">persist</span><span class="p">(</span><span class="nv">$myFirstComment</span><span class="p">);</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>
</pre></div>
</div>
<p>Even if you <em>persist</em> a new User that contains our new Comment this
code would fail if you removed the call to
<tt class="docutils literal"><span class="pre">EntityManager#persist($myFirstComment)</span></tt>. Doctrine 2 does not
cascade the persist operation to all nested entities that are new
as well.</p>
<p>More complicated is the deletion of all of a user&#8217;s comments when he is
removed from the system:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$user</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="s1">&#39;User&#39;</span><span class="p">,</span> <span class="nv">$deleteUserId</span><span class="p">);</span>

<span class="k">foreach</span> <span class="p">(</span><span class="nv">$user</span><span class="o">-&gt;</span><span class="na">getAuthoredComments</span><span class="p">()</span> <span class="k">AS</span> <span class="nv">$comment</span><span class="p">)</span> <span class="p">{</span>
    <span class="nv">$em</span><span class="o">-&gt;</span><span class="na">remove</span><span class="p">(</span><span class="nv">$comment</span><span class="p">);</span>
<span class="p">}</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">remove</span><span class="p">(</span><span class="nv">$user</span><span class="p">);</span>
<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>
</pre></div>
</div>
<p>Without the loop over all the authored comments Doctrine would use
an UPDATE statement only to set the foreign key to NULL and only
the User would be deleted from the database during the
flush()-Operation.</p>
<p>To have Doctrine handle both cases automatically we can change the
<tt class="docutils literal"><span class="pre">User#commentsAuthored</span></tt> property to cascade both the &#8220;persist&#8221;
and the &#8220;remove&#8221; operation.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">User</span>
<span class="p">{</span>
    <span class="c1">//...</span>
    <span class="sd">/**</span>
<span class="sd">     * Bidirectional - One-To-Many (INVERSE SIDE)</span>
<span class="sd">     *</span>
<span class="sd">     * @OneToMany(targetEntity=&quot;Comment&quot;, mappedBy=&quot;author&quot;, cascade={&quot;persist&quot;, &quot;remove&quot;})</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="nv">$commentsAuthored</span><span class="p">;</span>
    <span class="c1">//...</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Even though automatic cascading is convenient it should be used
with care. Do not blindly apply cascade=all to all associations as
it will unnecessarily degrade the performance of your application.
For each cascade operation that gets activated Doctrine also
applies that operation to the association, be it single or
collection valued.</p>
<div class="section" id="persistence-by-reachability-cascade-persist">
<h3>9.6.1. Persistence by Reachability: Cascade Persist<a class="headerlink" href="#persistence-by-reachability-cascade-persist" title="Permalink to this headline">¶</a></h3>
<p>There are additional semantics that apply to the Cascade Persist
operation. During each flush() operation Doctrine detects if there
are new entities in any collection and three possible cases can
happen:</p>
<ol class="arabic simple">
<li>New entities in a collection marked as cascade persist will be
directly persisted by Doctrine.</li>
<li>New entities in a collection not marked as cascade persist will
produce an Exception and rollback the flush() operation.</li>
<li>Collections without new entities are skipped.</li>
</ol>
<p>This concept is called Persistence by Reachability: New entities
that are found on already managed entities are automatically
persisted as long as the association is defined as cascade
persist.</p>
</div>
</div>
<div class="section" id="orphan-removal">
<h2>9.7. Orphan Removal<a class="headerlink" href="#orphan-removal" title="Permalink to this headline">¶</a></h2>
<p>There is another concept of cascading that is relevant only when removing entities
from collections. If an Entity of type <tt class="docutils literal"><span class="pre">A</span></tt> contains references to privately
owned Entities <tt class="docutils literal"><span class="pre">B</span></tt> then if the reference from <tt class="docutils literal"><span class="pre">A</span></tt> to <tt class="docutils literal"><span class="pre">B</span></tt> is removed the
entity <tt class="docutils literal"><span class="pre">B</span></tt> should also be removed, because it is not used anymore.</p>
<p>OrphanRemoval works with one-to-one, one-to-many and many-to-many associations.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When using the <tt class="docutils literal"><span class="pre">orphanRemoval=true</span></tt> option Doctrine makes the assumption
that the entities are privately owned and will <strong>NOT</strong> be reused by other entities.
If you neglect this assumption your entities will get deleted by Doctrine even if
you assigned the orphaned entity to another one.</p>
</div>
<p>As a better example consider an Addressbook application where you have Contacts, Addresses
and StandingData:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">namespace</span> <span class="nx">Addressbook</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">Doctrine\Common\Collections\ArrayCollection</span><span class="p">;</span>

<span class="sd">/**</span>
<span class="sd"> * @Entity</span>
<span class="sd"> */</span>
<span class="k">class</span> <span class="nc">Contact</span>
<span class="p">{</span>
    <span class="sd">/** @Id @Column(type=&quot;integer&quot;) @GeneratedValue */</span>
    <span class="k">private</span> <span class="nv">$id</span><span class="p">;</span>

    <span class="sd">/** @OneToOne(targetEntity=&quot;StandingData&quot;, orphanRemoval=true) */</span>
    <span class="k">private</span> <span class="nv">$standingData</span><span class="p">;</span>

    <span class="sd">/** @OneToMany(targetEntity=&quot;Address&quot;, mappedBy=&quot;contact&quot;, orphanRemoval=true) */</span>
    <span class="k">private</span> <span class="nv">$addresses</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">addresses</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ArrayCollection</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">newStandingData</span><span class="p">(</span><span class="nx">StandingData</span> <span class="nv">$sd</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">standingData</span> <span class="o">=</span> <span class="nv">$sd</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">removeAddress</span><span class="p">(</span><span class="nv">$pos</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nb">unset</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">addresses</span><span class="p">[</span><span class="nv">$pos</span><span class="p">]);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now two examples of what happens when you remove the references:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="nv">$contact</span> <span class="o">=</span> <span class="nv">$em</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="s2">&quot;Addressbook\Contact&quot;</span><span class="p">,</span> <span class="nv">$contactId</span><span class="p">);</span>
<span class="nv">$contact</span><span class="o">-&gt;</span><span class="na">newStandingData</span><span class="p">(</span><span class="k">new</span> <span class="nx">StandingData</span><span class="p">(</span><span class="s2">&quot;Firstname&quot;</span><span class="p">,</span> <span class="s2">&quot;Lastname&quot;</span><span class="p">,</span> <span class="s2">&quot;Street&quot;</span><span class="p">));</span>
<span class="nv">$contact</span><span class="o">-&gt;</span><span class="na">removeAddress</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>

<span class="nv">$em</span><span class="o">-&gt;</span><span class="na">flush</span><span class="p">();</span>
</pre></div>
</div>
<p>In this case you have not only changed the <tt class="docutils literal"><span class="pre">Contact</span></tt> entity itself but
you have also removed the references for standing data and as well as one
address reference. When flush is called not only are the references removed
but both the old standing data and the one address entity are also deleted
from the database.</p>
</div>
<div class="section" id="filtering-collections">
<h2>9.8. Filtering Collections<a class="headerlink" href="#filtering-collections" title="Permalink to this headline">¶</a></h2>
<p>Collections have a filtering API that allows to slice parts of data from
a collection. If the collection has not been loaded from the database yet,
the filtering API can work on the SQL level to make optimized access to
large collections.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Doctrine\Common\Collections\Criteria</span><span class="p">;</span>

<span class="nv">$group</span>          <span class="o">=</span> <span class="nv">$entityManager</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="s1">&#39;Group&#39;</span><span class="p">,</span> <span class="nv">$groupId</span><span class="p">);</span>
<span class="nv">$userCollection</span> <span class="o">=</span> <span class="nv">$group</span><span class="o">-&gt;</span><span class="na">getUsers</span><span class="p">();</span>

<span class="nv">$criteria</span> <span class="o">=</span> <span class="nx">Criteria</span><span class="o">::</span><span class="na">create</span><span class="p">()</span>
    <span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="nx">Criteria</span><span class="o">::</span><span class="na">expr</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">eq</span><span class="p">(</span><span class="s2">&quot;birthday&quot;</span><span class="p">,</span> <span class="s2">&quot;1982-02-17&quot;</span><span class="p">))</span>
    <span class="o">-&gt;</span><span class="na">orderBy</span><span class="p">(</span><span class="k">array</span><span class="p">(</span><span class="s2">&quot;username&quot;</span> <span class="o">=&gt;</span> <span class="nx">Criteria</span><span class="o">::</span><span class="na">ASC</span><span class="p">))</span>
    <span class="o">-&gt;</span><span class="na">setFirstResult</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="o">-&gt;</span><span class="na">setMaxResults</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span>
<span class="p">;</span>

<span class="nv">$birthdayUsers</span> <span class="o">=</span> <span class="nv">$userCollection</span><span class="o">-&gt;</span><span class="na">matching</span><span class="p">(</span><span class="nv">$criteria</span><span class="p">);</span>
</pre></div>
</div>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">You can move the access of slices of collections into dedicated methods of
an entity. For example <tt class="docutils literal"><span class="pre">Group#getTodaysBirthdayUsers()</span></tt>.</p>
</div>
<p>The Criteria has a limited matching language that works both on the
SQL and on the PHP collection level. This means you can use collection matching
interchangeably, independent of in-memory or sql-backed collections.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">use</span> <span class="nx">Doctrine\Common\Collections</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">Criteria</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">static</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">create</span><span class="p">();</span>
    <span class="sd">/**</span>
<span class="sd">     * @param Expression $where</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">where</span><span class="p">(</span><span class="nx">Expression</span> <span class="nv">$where</span><span class="p">);</span>
    <span class="sd">/**</span>
<span class="sd">     * @param Expression $where</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">andWhere</span><span class="p">(</span><span class="nx">Expression</span> <span class="nv">$where</span><span class="p">);</span>
    <span class="sd">/**</span>
<span class="sd">     * @param Expression $where</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">orWhere</span><span class="p">(</span><span class="nx">Expression</span> <span class="nv">$where</span><span class="p">);</span>
    <span class="sd">/**</span>
<span class="sd">     * @param array $orderings</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">orderBy</span><span class="p">(</span><span class="k">array</span> <span class="nv">$orderings</span><span class="p">);</span>
    <span class="sd">/**</span>
<span class="sd">     * @param int $firstResult</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setFirstResult</span><span class="p">(</span><span class="nv">$firstResult</span><span class="p">);</span>
    <span class="sd">/**</span>
<span class="sd">     * @param int $maxResults</span>
<span class="sd">     * @return Criteria</span>
<span class="sd">     */</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setMaxResults</span><span class="p">(</span><span class="nv">$maxResults</span><span class="p">);</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getOrderings</span><span class="p">();</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getWhereExpression</span><span class="p">();</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getFirstResult</span><span class="p">();</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">getMaxResults</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>You can build expressions through the ExpressionBuilder. It has the following
methods:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">andX($arg1,</span> <span class="pre">$arg2,</span> <span class="pre">...)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">orX($arg1,</span> <span class="pre">$arg2,</span> <span class="pre">...)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">eq($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">gt($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">lt($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">lte($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">gte($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">neq($field,</span> <span class="pre">$value)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">isNull($field)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">in($field,</span> <span class="pre">array</span> <span class="pre">$values)</span></tt></li>
<li><tt class="docutils literal"><span class="pre">notIn($field,</span> <span class="pre">array</span> <span class="pre">$values)</span></tt></li>
</ul>
</div>
</div>


              </div>
                </div>

            </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">



             
            <div id="searchbox" style="">
              <h3>Search</h3>
                <form class="search" action="http://readthedocs.org/search/project/" method="get">
                  <input type="text" name="q" size="18">
                  <input type="submit" value="Go">
                  <input type="hidden" name="selected_facets" value="project:Doctrine ORM">
                </form>
            </div>
            <h3><a href="../index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference internal" href="#">9. Working with Associations</a><ul>
<li><a class="reference internal" href="#association-example-entities">9.1. Association Example Entities</a></li>
<li><a class="reference internal" href="#establishing-associations">9.2. Establishing Associations</a></li>
<li><a class="reference internal" href="#removing-associations">9.3. Removing Associations</a></li>
<li><a class="reference internal" href="#association-management-methods">9.4. Association Management Methods</a></li>
<li><a class="reference internal" href="#synchronizing-bidirectional-collections">9.5. Synchronizing Bidirectional Collections</a></li>
<li><a class="reference internal" href="#transitive-persistence-cascade-operations">9.6. Transitive persistence / Cascade Operations</a><ul>
<li><a class="reference internal" href="#persistence-by-reachability-cascade-persist">9.6.1. Persistence by Reachability: Cascade Persist</a></li>
</ul>
</li>
<li><a class="reference internal" href="#orphan-removal">9.7. Orphan Removal</a></li>
<li><a class="reference internal" href="#filtering-collections">9.8. Filtering Collections</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="working-with-objects.html"
                                  title="previous chapter">8. Working with Objects</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="events.html"
                                  title="next chapter">10. Events</a></p>
  
    <h3>This Page</h3>
    <ul class="this-page-menu">
      
        <li><a href="../_sources/reference/working-with-associations.txt"
               rel="nofollow">Show Source</a></li>
      
      
        <li><a href="https://github.com/doctrine/doctrine2/blob/master/docs/en/reference/working-with-associations.rst">
          Show on GitHub</a></li>
        <li><a href="https://github.com/doctrine/doctrine2/edit/master/docs/en/reference/working-with-associations.rst">
          Edit on GitHub</a></li>
      
    </ul>
  

        </div>
      </div>
          <div class="clearer"></div>
        </div>

          <div class="footer">
              &copy; Copyright 2010-12, Doctrine Project Team.
              Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
            <br/>
            <a target="_BLANK" href="http://www.servergrove.com"><img src="http://www.doctrine-project.org/images/servergrove.jpg" /></a>      <br/><br/>
            <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
              <input type="hidden" name="cmd" value="_s-xclick" />
              <input type="hidden" name="hosted_button_id" value="BAE2E3XANQ77Y" />
              <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" />
              <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
            </form>
          </div>
 <!-- End original user content -->


<br/>
<br/>
<br/>


<style type="text/css">
  #version_menu, .rtd-badge.rtd {
    -webkit-transition: all 0.25s 0.75s;
    transition: all 0.25s 0.75s;
  }
  .footer_popout:hover #version_menu, .footer_popout:hover .rtd-badge.rtd {
    -webkit-transition: all 0.25s 0s;
    transition: all 0.25s 0s;
  }
  .rtd-badge {
    position: fixed;
    display: block;
    bottom: 5px;
    height: 40px;
    text-indent: -9999em;
    border-radius: 3px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.2) inset;
    -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.2) inset;
    -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.2) inset;
  }
  #version_menu {
    position: fixed;
    visibility: hidden;
    opacity: 0;
    bottom: 11px;
    right: 47px;
    list-style-type: none;
    margin: 0;
  }
  .footer_popout:hover #version_menu {
    visibility: visible;
    opacity: 1;
    right: 166px;
  }
  #version_menu li {
    display: block;
    float: right;
  }
  #version_menu li a {
    display: block;
    padding: 6px 10px 4px 10px;
    margin: 7px 7px 0 0;
    font-weight: bold;
    font-size: 14px;
    height: 20px;
    line-height: 17px;
    text-decoration: none;
    color: #fff;
    background: #8ca1af url(//media.readthedocs.org//images/gradient-light.png) bottom left repeat-x;
    border-radius: 3px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    box-shadow: 0 1px 1px #465158;
    -moz-box-shadow: 0 1px 1px #465158;
    -webkit-box-shadow: 0 1px 1px #465158;
    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
  }
  #version_menu li a:hover {
    text-decoration: none;
    background-color: #697983;
    box-shadow: 0 1px 0px #465158;
    -moz-box-shadow: 0 1px 0px #465158;
    -webkit-box-shadow: 0 1px 0px #465158;
  }
  .rtd-badge.rtd {
    background: #3b4449 url(//media.readthedocs.org//images/badge-rtd.png) scroll top left no-repeat;
    border: 1px solid #282E32;
    width: 41px;
    right: 5px;
  }
  .footer_popout:hover .rtd-badge.rtd {
    width: 160px;
  }
  .rtd-badge.revsys { background: #465158 url(//media.readthedocs.org//images/badge-revsys.png) top left no-repeat;
    border: 1px solid #1C5871;
    width: 290px;
    right: 173px;
  }
  .rtd-badge.revsys-inline-sponsored {
    position: inherit;
    margin-left: auto;
    margin-right: 175px;
    margin-bottom: 5px;
    background: #465158 url(//media.readthedocs.org//images/badge-revsys.png) top left no-repeat;
    border: 1px solid #1C5871;
    width: 290px;
    right: 173px;
  }
  .rtd-badge.revsys-inline {
    position: inherit;
    margin-left: auto;
    margin-right: 175px;
    margin-bottom: 5px;
    background: #465158 url(//media.readthedocs.org//images/badge-revsys-sm.png) top left no-repeat;
    border: 1px solid #1C5871;
    width: 205px;
    right: 173px;
  }

</style>
<div class="rtd_doc_footer">
  <div class="footer_popout">
    <a href="//readthedocs.org/projects/doctrine-orm/?fromdocs=doctrine-orm" class="rtd-badge rtd"> Brought to you by Read the Docs</a>
    <ul id="version_menu">
      
        <li><a href="/en/latest/">latest</a></li>
      
    </ul>
  </div>
</div>
<!-- RTD Analytics Code -->
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-17997319-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>




      </div>

      <div id="bot-rcnr">
        <div class="tl"><!-- corner --></div>
      </div>
    </div>

  <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
  </script>
  <script type="text/javascript">
  _uacct = "UA-288343-7";
  urchinTracker();
  </script>
  <a class="githublink" href="http://github.com/doctrine"><img src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
  </body>
</html>