2011-04-07 89 views
8

我使用find('all')函数从我的数据库中检索帖子记录,但是这也会返回所有与帖子模型相关联的用户信息,有很多关系。检索模型,但没有获取关联模型 - CakePHP

其缺点是用户模型包含密码和其他重要信息。这被认为是一个安全问题?我无法回应关于这个观点的信息。

感谢


编辑:

我修改了代码,但我仍然得到相关的模型。

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

任何想法?

回答

25

你有几个选择。您可以设置一个模型recursive属性:

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

Alterantively,您可以指定recursive作为一个选项来搜索:

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

您也可以在安置自己的模型中使用Containable行为。在这种情况下,你可以指定一个空集:

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

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

或者,在查询中指定:

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

Containable行为的好处是,当你以后关联其他型号你的文章。假设你实现了一个Tag模型。现在,你想找到它的标签后,而不是使用模式:

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

感谢您的意见。我尝试了'contains'=> false方法,但由于某种原因它仍然返回关联的模型。查看我的代码编辑 – AlexBrand 2011-04-07 20:44:52

+0

您是否在您的模型中包含“Containable”行为?看到我上面的编辑。 – 2011-04-07 21:15:45

+0

我错过了...非常感谢! – AlexBrand 2011-04-07 21:46:21

0

不要ü使用:

$this->Post->find('all')// If u access it from Post controller 

OR,

$this->User->Post->find('all')//If u access it from User controller 
+0

是...但我也得到了用户的模式。 – AlexBrand 2011-04-07 04:22:40

5

不一定。

但是,当您不需要时,您正在检索信息。现在不是一个问题,但请记住,当你有很多相关的数据

的这成为一个巨大的问题考虑(如果需要或0)您recursive属性设置为-1

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

这将拉动只从所选模型

或者更多的微调选择数据,可以使用中可容纳的行为:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

这可以让你选择哪个协会在检索数据时保持不变。

+0

非常感谢!我会研究它 – AlexBrand 2011-04-07 04:29:04

2

只是让你知道

$this->Model->recursive = -1 will remove all associations 
$this->Model->recursive = 0 will remove only hasMany assosiation (so it keeps belongsTo)