cakephp model association/join with same table [cl

2019-07-15 11:02发布

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

2条回答
你好瞎i
2楼-- · 2019-07-15 11:32

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

查看更多
爷的心禁止访问
3楼-- · 2019-07-15 11:43

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' 
            ), 
    ); 
} 
?>
查看更多
登录 后发表回答