在没有获得关联模型的情况下检索模型 - CakePHP

Ale*_*and 9 php cakephp

我使用find("全部")函数从我的数据库中检索后的记录,但是这也将返回与一个属于关联Post模型相关联的所有用户信息 - 的hasMany关系.

这样做的缺点是用户模型包含密码和其他重要信息.这被视为安全问题吗?我无处回应有关视图的信息.

谢谢


编辑:

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

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

有任何想法吗?

San*_*hal 27

你有几个选择.您可以recursive在模型上设置属性:

$this->Post->recursive = -1;
$posts = $this->Post->find('all');
Run Code Online (Sandbox Code Playgroud)

您可以指定recursive为搜索选项:

$posts = $this->Post->find('all', array(
    'recursive' => -1,
    'conditions' => ...
);
Run Code Online (Sandbox Code Playgroud)

您还可以使用ContainablePost模型中的行为.在这种情况下,您可以指定一个空集:

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

$this->Post->contain();
$posts = $this->Post->find('all');
Run Code Online (Sandbox Code Playgroud)

或者,在查询中指定:

$posts = $this->Post->find('all', array(
    'contain' => false,
);
Run Code Online (Sandbox Code Playgroud)

Containable行为的好处是您稍后将其他模型与您的帖子相关联.假设您实现了Tag模型.现在您要查找带有标签的帖子,但不是使用模型:

$posts = $this->Post->find('all', array(
    'contain' => array('Tag'),
);
Run Code Online (Sandbox Code Playgroud)


Joh*_*hnP 5

不必要.

但是,当您不需要时,您正在检索信息.现在这不是问题,但请记住,当您拥有大量关联数据时,这将成为一个巨大的问题

考虑将您的recursive属性设置为-1(或者如果需要,则为0)

$this->Model->recursive = -1;
Run Code Online (Sandbox Code Playgroud)

这将仅从所选模型中提取数据

或者,对于更精细的选择,您可以使用Containable行为:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

这允许您选择在检索数据时要保留的关联.