Cakephp 3 - limit () and contained model
<p>I have two models, named Post and Comment, which are linked by Post hasMany Comment and Comment belongsTo Post.
I want to fetch all posts with the first five comments each. I would use this code:</p>

<pre><code>$this-&gt;Posts-&gt;find('all')
     -&gt;contain([
        'Comments' =&gt; function($q) {
            return $q
                -&gt;order('created ASC')
                -&gt;limit(5);
}
]);
</code></pre>

<p>This works incorrectly with the limit(). Please help to solve this.
I used this example:
<a href="https://stackoverflow.com/questions/30241975/how-to-limit-contained-associations-per-record-group">How to limit contained associations per record/group?</a>
I tried to like this (in Post model):</p>

<pre><code>$this-&gt;hasOne('TopComments', [
    'className' =&gt; 'Comments',
    'strategy' =&gt; 'select',
    'conditions' =&gt; function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
        $query-&gt;leftJoin(
            ['CommentsFilter' =&gt; 'comments'],
            [
                'TopComments.post_id = CommentsFilter.post_id',
                'TopComments.created &lt; CommentsFilter.created'
            ]);
        return $exp-&gt;add(['CommentsFilter.id IS NULL']);
    }
]);
</code></pre>

<p>In Post controller:</p>

<pre><code>$this-&gt;Posts-&gt;find('all')
     -&gt;contain([
        'TopComments' =&gt; function($q) {
            return $q
                -&gt;order('TopComments.created ASC')
                -&gt;limit(5);
}
]);
</code></pre>

<p>Unfortunately this does not work. I do not know where I'm wrong.</p>