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.
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);
}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With