Cakephp如何在paginate使用unbind

黄舟
发布: 2023-03-03 16:40:01
原创
1592 人浏览过

cakephp的controller中的paginate是一个得到分页数据的函数.配合helper里的Paginator,可以很轻松的做出分页列表,排序的列表页面.
但由我开始学习用cakephp时,我就有一个问题一直困扰着我.
Model如何解除关联(unbind)?
正常的情况下,只要在find之前解除(unbind)我不需的model.就可以不去搜索这些modeld关联的数据表.而且在find完以后会自动返把之前我解除的model再次关联起来.以下是常用的使用方法


//user model
class User extends AppModel {

  var $name = 'User';
  var $belongsTo = array(
            'Profile' = array('className'=>'Profile','foreignKey'=>'user_id')
          )
}


运行以下代码


$this->User->unbind(array('belongsTo'=>array('Profile')));
$rs=$this->User->find();


$rs会是


array(
       'User'=>array(),
)


如果在find之前没有运行unbind,$rs将会是


array(
       'User'=>array(),
       'Profile'=>array()
)


但如果运行paginate就得不到同样的结果
code]
$this->User->unbind(array('belongsTo'=>array('Profile')));
$rs=$this->paginate('User');
[/code]
$rs的结果还是


array(
       'User'=>array(),
       'Profile'=>array()
)


为什么在paginate不能解除关联(unbind)?
原因是在find里在得到数据后,find会用model->resetAssociations();把所有关联(Association)还原.而paginate里使用了两次find.一次是得到总数,另一次得到分页显示的数据.所以返回的结果还是有Profile的内容.
解决方法:给unbind的第二个参数里赋上非ture的值.如果unbind的第二个参数是true,cakephp会把需要解除关联的数据库保存到model->__backAssociation里,当运行model->resetAssociations();会从model->__backAssociation把相关的关联的数据还原.所以以下代码就可以解决


$this->User->unbind(array('belongsTo'=>array('Profile')),false);
$rs=$this->paginate('User');


另外,如果在运行paginate()后,还需要使用model里的关联数据来find 数据.可以在app_model.php文件里增加以下代码


  /**
     * function description:turn off the Association,and return the the Association,.
   *                      the function working for Controller->paginate() and Model->bind().
   *                      the function will help you that get data form Controller->paginate() before unbind some 
   *                      Association for and rebind the remove of Association after get data.
   *                      if you don't neet to rebind Association,you can only use 
   *                      <br>   *                      $this->Models->unbind($params,false);<br>   *                      
     * @Date:2008-10-10
   *
   * $backAssociation = $this->ModelName->unbindAndPushModels(array('belongsTo'=>array('User')));
   * $result=$this->paginate('ModelName');
   * $this->ModelName->bind($backAssociation);//this action is to restore the model of assocication data.
   * * @param (类型)参数名 :描述
**/
Function unbindAndPushModels($params)
{
$backAssociation=array();
foreach ($params as $assoc => $models)
    {
      foreach ($models as $model)
      {
        If(isset($this->{$assoc}[$model]))
        {
          $backAssociation[$assoc][$model] = ;
          unset ($this->{$assoc}[$model]);
        }  
      }
    }
    Return $backAssociation;

 以上就是Cakephp如何在paginate使用unbind的内容,更多相关内容请关注PHP中文网(www.php.cn)!


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!