cakephp model association/join with same table [closed]
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.
精彩评论