但由我开始学习用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
* <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的内容。
