
Using unBindModel() in CakePHP
June 15, 2007If you have a lot of associations in your model setups, sometimes you dont want all that information to be returned in a query. The answer to this is to use the unBinModel() function. Using this you can unbind certain parts of your associations.
The easiest way to demonstrate this is with an example.
If you have a user model with the following associations:
var $hasMany = array(
'Worksheet' => array('className' => 'Worksheet'
),
'Login' => array('className' => 'Login'
),
'Expense' => array('className' => 'Expense'
)
);
var $belongsTo = array(
'Level' =>
array('className' => 'Level'),
'County' =>
array('className' => 'County'),
'Province' =>
array('className' => 'Province')
);
That is potentially a lot of information to get back each time you query the User.
So if we define
$this->User->unBindModel(array(hasMany => array('Login', 'Expense')));
before we call
$this->User->findAll();
we no longer return information from the Login and Expenses tables. This can be used for any of the associations and can cut down query times dramatically.
hi, nice and simple explanation, have subscribed to your blog.
Thanks for the comment, glad it helped you in some way. I guess I will have to do some more work and put up more articles now that I have someone actually reading along
Muchas Gracias por la explicación!
Muy buena!
Me sacaste de un problema!
Perdón pero no sé escribir en ingles =)
Saludos
Cecilia
Ningún problema, alegre ayudó
TIPS:
well the word ‘$hasMany’ in the
$this->User->unBindModel(array(hasMany => array(’Login’, ‘Expense’)));
is the model relationship in the app/model/User.php
so if you have other relationship like
$hasOne = ... or $hasAndBelongsToMany = ...
then the code will change as well
$this->User->unBindModel(array(hasAndBelongsToMany=> array(’Login’, ‘Expense’)));
Just for a short tips:
I spend 15 minutes figuring why my unBindModel() didn’t work.
Its because the “hasAndBelongsToMany” is the real word instead of “hasMany” in my case
Your example only works, because PHP is guessing right. If your set up your PHP to notice level, you’ll see the PHP notice, that hasMany as a constant is not specified and ‘hasMany’ is guessed.
Notifications can be a problem if you are using sessions and should generally be avoided, thus the correct version of your example code would be:
$this->User->unBindModel(array(‘hasMany’ => array(’Login’, ‘Expense’)));
That might also be the reason for the problems of asipo.
[...] Containable in CakePHP May 26, 2009 I’ve see a lot of traffic to my post about Using unBindModel in CakePHP and while it is a way of cutting down the data that is returned from a query, there is now a better [...]