unbindAll

By Brett ODonnell (cornernote)
Here is a simple way to unbind all models. Just put this function into your app_model.php

Model Class:

Download code <?php 
  
function unbindModelAll()
  {
    
$unbind = array();
    foreach (
$this->belongsTo as $model=>$info)
    {
      
$unbind['belongsTo'][] = $model;
    }
    foreach (
$this->hasOne as $model=>$info)
    {
      
$unbind['hasOne'][] = $model;
    }
    foreach (
$this->hasMany as $model=>$info)
    {
      
$unbind['hasMany'][] = $model;
    }
    foreach (
$this->hasAndBelongsToMany as $model=>$info)
    {
      
$unbind['hasAndBelongsToMany'][] = $model;
    }
    
parent::unbindModel($unbind);
  }
?>

 

Comments 183

CakePHP Team Comments Author Comments
 

Comment

1 recursive

You should be able to do the same thing by just setting $this->ModelName->recursive = -1; or $this->recursive = -1; if you are in the model.
Posted Dec 11, 2006 by gwoo
 

Comment

2 before running bindModel

You should be able to do the same thing by just setting $this->ModelName->recursive = -1; or $this->recursive = -1; if you are in the model.

That's true, but I think this is more for when you want to run bindModel on a 'clean slate'. Correct me if I'm wrong, but if you set recursive to -1 and then did a bindModel, you would not get the results of the Models associated with bindModel since there would be no recursion.

Also, Bret, I would replace the last line, parent::unbindModel with $this->unbindModel. You should get the same results but through inheritance, which gives you override abilities both in AppController and all controllers that extend it.
Posted Dec 11, 2006 by Tom OReilly
 

Comment

3 Another unbindAll

I found another one. This one looks better. I can't remember who made it but I thought I'd post it here. If your the author please feel free to post a comment and take the credit. My main point is that it wasn't me. :)

Model Class:

<?php 
  
function unbindAll($params = array())
  {
    foreach(
$this->__associations as $ass)
    {
      if(!empty(
$this->{$ass}))
      {
        
$this->__backAssociation[$ass] = $this->{$ass};
        if(isset(
$params[$ass]))
        {
          foreach(
$this->{$ass} as $model => $detail)
          {
            if(!
in_array($model,$params[$ass]))
            {
              
$this->__backAssociation array_merge($this->__backAssociation$this->{$ass});
              unset(
$this->{$ass}[$model]);
            }
          }
        }else
        {
          
$this->__backAssociation array_merge($this->__backAssociation$this->{$ass});
          
$this->{$ass} = array();
        }

      }
    }
    return 
true;
  }
?>
Posted Dec 27, 2006 by Brett ODonnell
 

Comment

4 Found The Author

The snippet above was written by Othman ouahbi (aka: CraZyLeGs)

The original can be downloaded from here:
http://othy.wordpress.com/2006/06/03/unbind-all-associations-except-some/
Posted Dec 27, 2006 by Brett ODonnell