Retrieve posts with their latest comment in CakePHP -
say have model post
, model comment
related follows:
post hasmany comment comment belongsto post
how use find('all')
retrieve every post
associated latest comment
?
i have tried defining hasone
relationship in post
as:
var $hasone = array('latestcomment' => array('classname' => 'comment', 'order' => 'latestcomment.created desc'));
but when post->find('all')
returns every post
multiple times, once per each comment
, latestcomment
set different comments
.
you can add 'limit' => 1 array of parameters return 1 comment.
alternatively, instead of defining relationship, can limit number of comments returned when perform find, using containable behaviour.
$this->post->find('all',array( 'contain' => array( 'comment' => array( 'order' => 'comment.created desc', 'limit' => 1 ) ) );
this useful if want filter related sets without defining relationships - author, or within date range, example.
make sure add containable behaviour model reference.
Comments
Post a Comment