开发者

cakephp model association/join with same table [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For开发者_高级运维 help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

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


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' 
            ), 
    ); 
} 
?>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜