Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving models without getting associated models - CakePHP

Tags:

php

cakephp

I use the find('all') function to retrieve the post records from my database, but this will also return all the User information that is associated with the Post model with a belongsTo - hasMany relationship.

The downside of this is that the user model contains password and other important information. Is this considered a security issue? I am nowhere echo-ing the information on the view.

Thanks


EDIT:

I modified my code but I am still getting the associated models.

        $this->set('posts_list',$this->Post->find('all',array('contain' => false, 'order' => array('Post.price ASC'))));

Any ideas?

like image 212
AlexBrand Avatar asked Apr 07 '11 04:04

AlexBrand


3 Answers

You have several options. You can set the recursive property on a model:

$this->Post->recursive = -1;
$posts = $this->Post->find('all');

Alterantively, you can specify recursive as an option to your search:

$posts = $this->Post->find('all', array(
    'recursive' => -1,
    'conditions' => ...
);

You can also use the Containable behaviour in your Post model. In that case you can specify an empty set:

class Post extends AppModel {
    var $actsAs = array('Containable');
}

$this->Post->contain();
$posts = $this->Post->find('all');

Or, specified in the query:

$posts = $this->Post->find('all', array(
    'contain' => false,
);

The upside for the Containable behaviour is when you later on associate other models with your post. Suppose that you implement a Tag model. Now you want to find a post with it's tags, but not the use model:

$posts = $this->Post->find('all', array(
    'contain' => array('Tag'),
);
like image 177
Sander Marechal Avatar answered Nov 15 '22 18:11

Sander Marechal


Not necessarily.

But you are retrieving information when you don't need it. It's not a problem now, but keep in mind this becomes a huge problem when you have a lot of associated data

Consider setting your recursive attribute to -1 (or 0 if needed)

$this->Model->recursive = -1;

This will pull data only from the selected model

Or for more fine tuned selection, you can use the Containable behavior : http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

This allows you to select which associations to keep when retrieving data.

like image 43
JohnP Avatar answered Nov 15 '22 19:11

JohnP


just so you know

$this->Model->recursive = -1 will remove all associations
$this->Model->recursive = 0 will remove only hasMany assosiation (so it keeps belongsTo)
like image 22
Arthur Kielbasa Avatar answered Nov 15 '22 20:11

Arthur Kielbasa