Thursday, November 4, 2010

Model: App Model

The find() method, as used previously, returns not only the data from the table/model identified, but all related data as well. This is usually a good thing, but typically it returns far too many levels of data than is necessary.

Edit /app/views/users/index.ctp and add the following line to the end of the file then browse to http://drug-ed.com/users/ to see what is returned for just one record:
<?php print_r($user); ?>
It may look something like this:
Array ( [User] => Array ( [id] => 1 [slug] => admin [username] => admin [password] => test [first_name] => test [last_name] => test [email] => naidim@gmail.com [email_verified] => 1 [carrier_id] => 1 [cell_number] => 5205551234 [created] => 2010-11-03 21:12:40 ) [Carrier] => Array ( [id] => 1 [name] => Verizon PCS [extension] => vtext.com ) [Reminder] => Array ( ) )
By default it should contain only what the current view requires, only returning more if the Containable behavior is set.

To limit the find() method for all models, create /app/app_model.php This model overrides the default AppModel and allows you to control the functionality of all models.
<?php
class AppModel extends Model {
    var $recursive = -1;
    var $actsAs = array('Containable');
}
?>
Now browse to http://drug-ed.com/users/ and you should see something more like this:
Array ( [User] => Array ( [id] => 1 [slug] => admin [username] => admin [password] => test [first_name] => test [last_name] => test [email] => naidim@gmail.com [email_verified] => 1 [carrier_id] => 1 [cell_number] => 5205551234 [created] => 2010-11-04 21:12:40 ) ) 
Go back and remove that last line from /app/views/users/index.ctp.

For details on Containable behavior http://book.cakephp.org/view/1323/Containable and using Containable with paginate http://book.cakephp.org/view/1232/Controller-Setup

Don't forget to add var $actsAs = array('Containable'); to the appropriate model (or AppModel) before you try to use contain();

Thanks to Matt Curry

No comments:

Post a Comment