cakephp model association/join with same table [closed]

社会主义新天地 提交于 2020-01-04 05:30:51

问题


I have a table that contains parents and children. I want to be able to build the model so that it returns the parents and their children i.e it associates with itself.

ID Name ParentID
1  Parent  0
2  Child1  1
3  Child2  1
4  Parent2 0
5  Child3  4

I use the following SQL

SELECT
 grp2.id,
 grp2.name
FROM wp_bp_groups grp1
LEFT JOIN wp_bp_groups grp2
 ON grp2.parent_id = grp1.id
WHERE grp1.id = '$parent_id'
ORDER BY grp2.name

回答1:


You could try something like this:

<?php  
class Group extends AppModel { 

 var $name = 'Group'; 

 var $belongsTo = array( 
        'ParentGroup' => 
            array('className' => 'Group', 
                  'foreignKey' => 'parent_id' 
        ), 
     ); 

 var $hasMany = array( 
    'ChildGroup' => 
            array('className' => 'Group', 
                  'foreignKey' => 'parent_id' 
            ), 
    ); 
} 
?>



回答2:


You're looking for Tree behaviour, which allows easy management of hierarchical data.



来源:https://stackoverflow.com/questions/5304928/cakephp-model-association-join-with-same-table

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