频道栏目
首页 > 资讯 > cakephp > 正文

Cakephp如何在paginate使用unbind

16-01-08        来源:[db:作者]  
收藏   我要投稿

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
*
*$this->Models->unbind($params,false);
*

* @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;
相关TAG标签
上一篇:CAKEPHP 脚手架 Scaffolding
下一篇:ZendFrameWork 如何在一个工程当中将不同的访问导向不同的模块?
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站