- 论坛徽章:
- 0
|
作者:bkkkd
原文地址:Cakephp如何在paginate使用unbind
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就得不到同样的结果
- $this->User->unbind(array('belongsTo'=>array('Profile')));
- $rs=$this->paginate('User');
复制代码
$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把相关的关联的数据还原.所以以下代码就可以解决
code]
$this->User->unbind(array('belongsTo'=>array('Profile')),false);
$rs=$this->paginate('User');
[/code]
另外,如果在运行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
- * <code>
- * $this->Models->unbind($params,false);
- * </code>
- * @Date:2008-10-10
- * <code>
- * $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.
- * </code
- * @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
[ 本帖最后由 bkkkd 于 2008-10-11 10:00 编辑 ] |
|