假设有一个model叫Company,另一个叫Member。
Company和Member是1:n的关系。
如果Company中加了hasmany的关系。
那执行$Company->find()的时候,是不是会把所有的member数据也一次取出?
如果是,这样必然导致性能低下,甚至站点瘫痪。
参看文章:http://book.cakephp.org/complete/66/Models#Associations-Linking-Models-Together-78
以下摘自cakephp手册
- hasone
- Once this association has been defined, find operations on the User model will also fetch a related Profile record if it exists
- belongsto
- Once this association has been defined, find operations on the Profile model will also fetch a related User record if it exists:
- hasmany
- Once this association has been defined, find operations on the User model will also fetch related Comment records if they exist:
- 但是提供了’limit‘, ‘offset‘, ‘finderQuery‘,来让你自己决定如何取many端
- hasAndBelongsToMany(HABTM)
- Once this association has been defined, find operations on the Recipe model will also fetch related Tag records if they exist:
结论:
- 如上所示,find操作会取出所有定义了的related的Model数据,需要谨慎设置 hasmany和habtm。
- 根据mannual来看,cakephp在执行find的时候是不会递归取关系数据的。比如取company的时候会取出members数据,但是不会递归去除member的company数据。
重要补充
cakephp可以指定find操作时,递归取数据的层数。上面结论的第二条错误。