I'm starting to use cakePhp to make a small website. I defined relationship between table, and I want to know: will those related data loaded every time? Because depending of the current view, some linked table will never be used, and actually they are queried every time.
It's a big cost for what it brings to us, no?
So how to have this kind of relationship and activate it only when we need it? Some kind of lazy loading which loads the related table only if I need it?
Cake facilates to unbind your non require model befire you run your query.
$this->unbindModel(array($relation => $model));
$relation - Is your relation with your other model.
$model - Model Name.
eg: $this->Library->unbindModel(array('belongsTo' => array('Membership'),),false);
http://bakery.cakephp.org/articles/cornernote/2006/12/10/unbindall
Try using proper recursive
level first, After that use unBindModel
as stated by @riky.
Don't do something silly like using recursive
level 2 and after that unbinding all the unwanted models.
will those related data loaded every time?
The data: no. The models: yes, related models will be initialized.
Because depending of the current view, some linked table will never be used, and actually they are queried every time.
Use containable or recursive
.
It's a big cost for what it brings to us, no?
Well, maybe, if you have a lot of relationships. Otherwise, it's just more convenient.
So how to have this kind of relationship and activate it only when we need it? Some kind of lazy loading which loads the related table only if I need it?
I don't think lazy loading is available. You can always bindModel on the fly. But again, I'd say you are worrying about tiny optimizations. Loading those models would usually take a few milisec in each request.