debuggable

 
Contact Us
 

Toggling Associations in CakePHP Models

Posted on 8/1/06 by Felix Geisendörfer

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

Alright, associations in CakePHP are a wonderful thing. But sometimes you just want to turn them off for one single findAll() call because you don't need the bulk of related items. So since I didn't find any existing way of doing this I came up with my own one:

class CakeModel extends AppModel
{
  function turnAssociationsOn()
  {  
    $this->_tempRestoreVariables(array('_oneToOne', '_belongsToOther', '_oneToMany', '_manyToMany'));
  }
 
  function turnAssociationsOff()
  {   
    $this->_tempSaveVariables(array('_oneToOne', '_belongsToOther', '_oneToMany', '_manyToMany'), array());   
  }
 
  function _tempSaveVariables($variables, $replaceWith = NULL)
  {
    foreach ($variables as $nr => $variable)
    {
        $this->{$variable.'Tmp'} = @$this->{$variable};
        $this->{$variable} = $replaceWith;
    }
  }
 
  function _tempRestoreVariables($variables)
  {
    foreach ($variables as $nr => $variable)
    {
        $this->{$variable} = @$this->{$variable.'Tmp'};
        unset($this->{$variable.'Tmp'});
    }
  }  
}

For people who don't want to go into extending the Model class they it should work to copy the functions inside of CakeModel into their specific Model where they want to use them.

I hope this is helpful to somebody ...

Update: I fixed a little bug that will occur if you toggle associations for save() or generateFields(). The problem was I was replacing the association variables with NULL instead of array() which is their default value which can lead to some PHP warning here and there.
Important: This is a temporary fix. I talked to Nate and he is working on this feature for Bundt (Cake 1.0). In the new release there will be a parameter depth's for association that you can set to '0' if you want to deactivate them.

--Felix

 
&nsbp;

You can skip to the end and add a comment.

cake baker » Toggling associations said on Jan 09, 2006:

[...] ThinkingPHP has published an idea how you can activate/deactivate associations for a findAll() call. Nice. There is also a RFC (request for comment) for integrating this feature into the core of CakePHP. [...]

gwoo  said on Jan 20, 2006:

RC3 will have this fully implemented. look for recursive in the api.

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.