azv
azv

Reputation: 1593

How to limit number of records from associated model

In a simple CakePHP model where User hasMany Item (and Item belongsTo User)- Suppose 50 users, have each 10 items. How can I find() only 5 users, each with the latest 5 items he has? When I impose a limit in the find, it only limits the number of users, not the number of associated Items.

Upvotes: 2

Views: 5760

Answers (2)

Filipe Teles
Filipe Teles

Reputation: 51

An option. In your controller:

$this->User->hasMany['Item']['limit'] = 1;

This will limit the number of items. I didn't test the order, but this should work:

$this->User->hasMany['Item']['order'] = 'Item DESC';

Upvotes: 5

Dan Berlyoung
Dan Berlyoung

Reputation: 1689

Just spec the limit attribute in your hasMany model declaration.

var $hasMany = array(
    'Comment' => array(
        'className'     => 'Comment',
        'foreignKey'    => 'user_id',
        'conditions'    => array('Comment.status' => '1'),
        'order'    => 'Comment.created DESC',
        'limit'        => '5',
        'dependent'=> true
    )
);  

(Appropriate props to the CakePHP Book page that I stole this code from.)

Upvotes: 7

Related Questions