Foreign key definition in cakePhp: Lazy loading?

你说的曾经没有我的故事 提交于 2020-01-07 07:11:07

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7440589/foreign-key-definition-in-cakephp-lazy-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!