Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I filter deep associations in CakePHP
    text
    copied!<p>I have the following tables: binders, docs, users, docs_users. Doc belongsTo Binder, Doc hasAndBelongsToMany User. </p> <p>I want to get binders and their associated docs for the user that is currently logged in (the associated user_id in the docs_users table).</p> <p>I have tried Containable and find('all') with joins, conditions, etc. but I can't figure out how to remove the Docs that are from Users who are not associated in the docs_users table.</p> <p>This code does NOT work:</p> <pre><code>$binders = $this-&gt;Binder-&gt;find( 'all', array( 'joins' =&gt; array( array( 'table' =&gt; 'binders_users', 'alias' =&gt; 'BindersUser', 'type' =&gt; 'inner', 'foreignKey' =&gt; false, 'conditions'=&gt; array( 'BindersUser.binder_id = Binder.id', 'BindersUser.user_id = ' . $this-&gt;Auth-&gt;user('id') ) ), array( 'table' =&gt; 'docs', 'alias' =&gt; 'Doc', 'type' =&gt; 'left', 'foreignKey' =&gt; false, 'conditions'=&gt; array( 'Doc.binder_id = Binder.id', ) ), array( 'table' =&gt; 'docs_users', 'alias' =&gt; 'DocsUser', 'type' =&gt; 'left', 'foreignKey' =&gt; false, 'conditions'=&gt; array( 'DocsUser.doc_id = Doc.id', 'DocsUser.user_id = ' . $this-&gt;Auth-&gt;user('id') ) ) ), 'recursive'=&gt;0 ) ); $this-&gt;set('binders', $binders); </code></pre> <p>And neither does this:</p> <pre><code>$this-&gt;Binder-&gt;recursive = 2; $this-&gt;Binder-&gt;Behaviors-&gt;attach('Containable'); $this-&gt;Binder-&gt;contain(array( 'Branch', 'Doc' =&gt; array( 'User' =&gt; array( 'DocsUser' =&gt; array( 'conditions' =&gt; array('id = "17"') ) ) ) )); $binders = $this-&gt;Binder-&gt;find('all'); </code></pre> <p>Any help from you seasoned pros would be great! Thanks!</p> <p><strong>Alternative/Simplified Solutions?</strong></p> <p>This works if I just want to get binders to which users have permissions. Short and sweet. However, it will still send ALL associated docs through, which is NOT the behavior I want. It needs to only pass on the docs to which the user has permissions (as described previously).</p> <pre><code>$binders = $this-&gt;Binder-&gt;find( 'all', array( 'joins' =&gt; array( array( 'table' =&gt; 'binders_users', 'alias' =&gt; 'BindersUser', 'type' =&gt; 'inner', 'foreignKey' =&gt; false, 'conditions'=&gt; array( 'BindersUser.binder_id = Binder.id', 'BindersUser.user_id = ' . $this-&gt;Auth-&gt;user('id') ) ) ) ) ); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload