开发者

Pagination with recursion while using loadModel

In my "Reports" controller, which is just a dummy controller without any actual database, I'm trying to generate a paginated view of other models. For example, to generate paginated view of "Transactions" model I'm doing the following:

$this->loadModel('Transactions');
$this->Transactions->开发者_StackOverflow社区bindModel(array('belongsTo'=>array('Item'=>array('className'=>'Item'),'Member'=>array('className'=>'Member'))));
$results = $this->paginate('Transactions',null,array('recursive'=>1));

But this is not giving me associated data from Items and Members. If I do a

$this->Transactions->find('all',array('recursive'=>1))

I get the associated data, but not paginated. How will I get paginated view which includes the associated data too?


Two things: First, even when plural model names can work for some odd reason, the convention is that model names are singular, like $this->loadModel('Transaction');. See the manual on naming conventions.

Second, forget about recursive and go for the Containable behavior. Frankly, it's so useful that I wonder why it isn't the default process (perhaps because Containable got created when the framework was very mature). Matt has a good book explaining why Containable is good (download it, really, it's almost mandatory :D ). But to help even more, I'm going to tell you exactly how you solve your issue with containable:

1) Define the associations in the models, like:

In Transaction model:

var $belongsTo = array(
    'Item' => array(
        'className' => 'Item',
        'foreignKey' => 'item_id',
    )
);

In Item model:

var $hasMany = array(
    'Transaction' => array(
        'className' => 'Transaction',
        'foreignKey' => 'item_id',
        'dependent' => true,
        'exclusive' => true,
    )
);

Do the same for the Member model.

2) Create an app_model.php file in /app/ with this code: (The $actsAs variable here within the AppModel class tells all models to use Containable)

<?php
class AppModel extends Model {
    var $recursive = -1;
    var $actsAs = array('Containable');
}
?>

3) In the Reports Controller, change the code to something like this: (The contain parameter is an array of all the associated models that you want to include. You can include only one assoc. model, or all, or whatever you want).

$this->loadModel('Transaction');
$this->paginate = array('Transaction' => array('contain' => array('Item', 'Member')));      
$results = $this->paginate('Transaction');

And that's it!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜