3

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:

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

This works incorrectly with the limit(). Please help to solve this. I used this example: How to limit contained associations per record/group? I tried to like this (in Post model):

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

In Post controller:

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

Unfortunately this does not work. I do not know where I'm wrong.

Community
  • 1
  • 1
lupi
  • 91
  • 1
  • 4
  • Possible duplicate of [How to limit contained associations per record/group?](http://stackoverflow.com/questions/30241975/how-to-limit-contained-associations-per-record-group) – arilia Jul 20 '16 at 09:39

1 Answers1

6

You should try this

In your model

$this->hasMany('Comments', [
    'foreignKey' => 'post_id'
]);

In your controller

$this->Posts->find()
     ->contain([
        'Comments' => function($q) {
            return $q
                ->order(['created' =>'ASC'])
                ->limit(5);
}
]);
  • 3
    Unfortunately it does not work. CakePHP is a powerful framework, but sometimes it happens that the basic things do not work as they should. – lupi Jul 20 '16 at 12:00
  • yes it does not work in cakephp 3 the using of the limit in the contain condition – Andrewboy Apr 06 '21 at 19:26