• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Cakephp如何在paginate使用unbind

php 搞代码 3年前 (2022-01-22) 26次浏览 已收录 0个评论

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() be¥本文来%源[email protected]搞@^&代*@码)网5搞gaodaima代码fore 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如何在paginate使用unbind的内容,更多相关内容请关注搞代码(www.gaodaima.com)!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Cakephp如何在paginate使用unbind

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址