Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 - limit () and contained model

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.

like image 979
lupi Avatar asked Apr 01 '26 07:04

lupi


1 Answers

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);
}
]);