Aug 21

Cakephp 学习日志 (二) 不指定

bkkkd , 07:54 , 开发应用 , 评论(0) , 引用(0) , 阅读(39787) , Via 本站原创 | |

使用 bindModel() 和 unbindModel() 实时地改变关联关系
有的时候可能你会需要实时地,动态的改变model的关联关系,比如在一个异常情况下。特别是LazyLoad的问题,有的时候我们并需要一个完整的model,所以我们可以使用 bindModel() 和 unbindModel()来绑定或者解除绑定关联对象。

代码说话,Start:

leader.php and follower.php  
<?php  
  
class Leader extends AppModel  
{  
    var $name = 'Leader';  
  
    var $hasMany = array(  
        'Follower' => array(  
            'className' => 'Follower',  
            'order'     => 'Follower.rank'  
        )  
    );  
}  
  
?>  
  
<?php  
  
class Follower extends AppModel  
{  
    var $name = 'Follower';  
}  
  
?>  

上述两个Model,在Leader Model中,有一个hasMany关联,定义了 "Leader hasMany Followers" 这样的关系。下面我们演示如何在Controller中动态地解除这种关联绑定。

leaders_controller.php (partial)  
function someAction()  
{  
    //This fetches Leaders, and their associated Followers  
    $this->Leader->findAll();  
  
    //Let's remove the hasMany...  
    $this->Leader->unbindModel(array('hasMany' => array('Follower')));
    
    //Now a using a find function will return Leaders, with no Followers
    $this->Leader->findAll();

    //NOTE: unbindModel only affects the very next find function.
    //注意:unbindModel方法只作用一次,第二次find方法调用时则仍然是关联关系有效的
    //An additional find call will use the configured association information.

    //We've already used findAll() after unbindModel(), so this will fetch  
    //Leaders with associated Followers once again...  
    $this->Leader->findAll();  
}  

对于其他各种关联的unbindModel()的用法是类似的,你只需要更改名字和类型就可以了,下面介绍一些基础的Usage:
内文分页: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16]
Tags:
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]