Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Where:</strong> You do it in the model. That's <a href="http://bitfluxx.com/2008/01/23/cakephp-best-practices-fat-models-and-skinny-controllers.html" rel="nofollow">good practice</a>.</p> <p><strong>How:</strong> I see two valid methods (I mean, there's tons of alternatives, but these are the easiest and don't repeat code everywhere)</p> <ol> <li><p>Use <a href="http://book.cakephp.org/2.0/en/models/virtual-fields.html" rel="nofollow">Virtual Fields</a>. In your model do something like</p> <pre><code>public $virtualFields = array( 'rank' =&gt; '/*query*/' //sql query that get's the number you want ); </code></pre> <p>That will add a field (virtual, is not in the DB) everytime you do a find() of that model</p></li> <li><p>Create your own function in the model an call it whenever you want</p> <pre><code>public getRank($postID) { $post = $this-&gt;find('first', array('conditions'=&gt;array('id'=&gt;$postID); $rank = /*do the calculation you want*/ return $rank; } </code></pre> <p>You call that function from the controllers like find() or save() or any other</p> <pre><code>$this-&gt;Post-&gt;getRank($id); </code></pre> <p>If by any reason you want to have this rank <em>everytime</em> you call a Post, then in the <a href="http://book.cakephp.org/2.0/en/models/callback-methods.html" rel="nofollow">afterFind()</a> method of that post, add a call to that function:</p> <pre><code>public afterFind(array $results, boolean $primary = false) { parent::afterFind($results, $primary); foreach ($results as $i=&gt;$result) { $results[$i]['rank'] = $this-&gt;getRank($result['id']); } return $results; } </code></pre> <p>I didn't test the <em>afterFind</em> function. So change it to fit your needs.</p></li> </ol>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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