Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to limit the the number of row retrieved from an associated table in CakePHP?
    primarykey
    data
    text
    <p>Assuming two database tables: <code>Funds</code> and <code>Prices</code>, in which <code>Funds hasMany Prices</code>.</p> <p>What I wanted to do is to retrieve the latest 15 prices of a particular fund in a certain scenario. Is there a means in CakePHP to make a <code>$this-&gt;Fund-&gt;find('all')</code> call that would allow me to limit the number of rows to be retrieved from the associated <code>Price</code> table?</p> <p><em>Note that I prefer not setting the <code>'limit'</code> option in the <code>Fund</code> model's <code>$hasMany</code> variable.</em></p> <p><strong>Note on accepted answer [Nov 2]:</strong></p> <p><a href="https://stackoverflow.com/questions/1657363/how-to-limit-the-the-number-of-row-retrieved-from-an-associated-table-in-cakephp/1657391#1657391">In Jason's answer which I had accepted</a>, I personally opt for the <code>bindModel</code> solution as I felt despite feeling a bit “hack-y”, it bodes much better with me as to make a one-off override on the default Model bindings.</p> <p>The code I used is as follows:</p> <pre><code>$this-&gt;Fund-&gt;bindModel(array( 'hasMany' =&gt; array( 'Price' =&gt; array( 'limit' =&gt; 15, 'order' =&gt; 'Price.date DESC' ) ) ); </code></pre> <p>No <code>unbindModel</code> is necessary. More information could be read from <a href="http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly" rel="nofollow noreferrer">“3.7.6.6 Creating and Destroying Associations on the Fly”</a> in the CakePHP manual.</p>
    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