【问题标题】:Retrieving models without getting associated models - CakePHP在不获取关联模型的情况下检索模型 - CakePHP
【发布时间】:2011-04-07 04:13:48
【问题描述】:

我使用 find('all') 函数从我的数据库中检索帖子记录,但这也将返回与 Post 模型关联的所有用户信息,其中包含 belongsTo - hasMany 关系。

这样做的缺点是用户模型包含密码和其他重要信息。这被认为是一个安全问题吗?我没有在视图上回应信息。

谢谢


编辑:

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

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

有什么想法吗?

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    您有多种选择。您可以在模型上设置recursive 属性:

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

    或者,您可以指定recursive 作为搜索选项:

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

    您还可以在 Post 模型中使用 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 行为的好处是当您稍后将其他模型与您的帖子相关联时。假设您实现了一个标签模型。现在你想找到一个带有标签的帖子,而不是使用模型:

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

    【讨论】:

    • 感谢您的意见。我尝试了 'contain' => false 方法,但由于某种原因它仍然返回关联的模型。查看我的代码的编辑
    • 您的模型中是否包含Containable 行为?请参阅上面的编辑。
    • 我错过了...非常感谢!
    • 出色的工作节省了我的时间。感谢它是一个完美的方法。
    【解决方案2】:

    不一定。

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

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

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

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

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

    这允许您选择在检索数据时要保留哪些关联。

    【讨论】:

      【解决方案3】:

      让你知道

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

      【讨论】:

        【解决方案4】:

        你用这个吗:

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

        或者,

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多