[eluser]OverZealous[/eluser] @tomdelonge
A self relationship is just a named relationship. Do you understand how multiple relationships to the same object work? IE: the creater/editor relationship from Bug to User?
For self relationships, you are just relating one object to itself.
Remember, all relationships have to be described from both sides. other_field literally is just the name of the other (opposite) field in the relationship. Notice in the example below how the relationship key and other_field are just swapped between the two definitions.
Here's some (untested) code:
Code:
class Category extends DataMapper {
$has_one = array(
// NOTE: can't use the keyword 'parent' here, because it has meaning to DMZ.
'parentcategory' => array(
'class' => 'category',
'other_field' => 'childcategory'
)
);
categories
---+-----------+------------------
id | name | parentcategory_id
---+-----------+------------------
1 | ROOT | NULL
2 | Games | 1
3 | Work | 1
4 | Board | 2
Usage:
Code:
$root = new Category(1);
// create new category
$cat = new Category();
$cat->name = 'Private';
// there are actually 3 ways to save the relationship. See Save in the manual for other examples.
$cat->save(array('parentcategory' => $root));
// get root categories
$cats = $root->childcategory->get();
foreach($cats as $c) {
echo($c->name . "\n");
// recurse
foreach($c->childcategory->get() as $sub) {
echo(" - " . $sub->name . "\n");
}
}
// delete a child category
$root->delete_childcategory($cat);
It's really that simple, especially for $has_one self relationships. Feel free to choose better (shorter) names.
----------
One more option, you can use a simpler relationship name on one side of the relationship, like so: