Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This can be done using <a href="http://book.cakephp.org/view/1608/Virtual-fields" rel="nofollow">$virtualFields</a>:</p> <p>In the Vote model I add the following virtual field:</p> <pre><code>var $virtualFields = array( 'vote_count' =&gt; 'IFNULL( SUM( Vote.value ) , 0 )' ); </code></pre> <p>In the Person model I retrieve this every time by using the following $hasMany relationship:</p> <pre><code>var $hasMany = array('Vote' =&gt; array('fields' =&gt; array('vote_count'))); </code></pre> <p>Note that by default it will always retrieve every field in the Vote table, this will result in retrieving the 'vote_count' SUM field by default and will only show one row as expected if you were to write out the query in full.</p> <p>If you want to retrieve all of the rows and remove the SUM virtual field then you need to specify all the fields (as necessary) in the fields array except the 'vote_count' field e.g.</p> <pre><code>var $hasMany = array('Vote' =&gt; array('fields' =&gt; array('id', 'value'))); </code></pre> <p>I would suggest this is better controlled by having a couple of functions in the Person model as such, which will allow you to decide on the fly how you want to retrieve the votes:</p> <pre><code>function allWithVoteCounts() { $this-&gt;bindModel(array('hasMany' =&gt; array('Vote' =&gt; array( 'fields' =&gt; array('vote_count') ) ) )); return $this-&gt;find('all'); } function allVotes() { $this-&gt;bindModel(array('hasMany' =&gt; array('Vote' =&gt; array( 'fields' =&gt; array('id', 'user_id', 'person_id', 'value', 'date') ) ) )); return $this-&gt;find('all'); } </code></pre> <p>Then in the controller you can call:</p> <pre><code>$persons = $this-&gt;Person-&gt;allVotes(); </code></pre> <p>or</p> <pre><code>$persons = $this-&gt;Person-&gt;allWithVoteCounts(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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