|
Your question is about a reflexive association (an association from a
table to itself).
Let's assume your reflexive table has SQL name "Data", with columns
"id", "name" and "parent_id". On the Perl side we have to declare a
schema and declare the table within that schema (let's name it
"My::Data") :
DBIx::DataModel->Schema('Sch');
Sch->Table(qw/My::Data Data id/);
Next we declare the reflexive association, which creates methods
for retrieving the parent or the children of any record.
Sch->Association([qw/My::Data parent 0..1 id /],
[qw/My::Data children * parent_id/]);
Now we can connect the schema to the database and find the
root items
my $dbh = DBI->connect(...);
Sch->dbh($dbh);
my $roots = My::Data->select(-where => {parent_id => undef});
Each root object has a "children" method to find its children,
so it's easy to print the whole structure
foreach my $root (@$roots) {
print_tree($root, "");
}
sub print_tree {
my ($root, $offset) = @_;
print "$offset$root->{name}\n";
my $children = $root->children;
foreach my $child (@$children) {
print_tree($child, "$offset ");
}
}
Instead, we can tell the schema to auto-expand the association, and
then directly build the tree for each root
use constant true => 1;
My::Data->AutoExpand('children');
foreach my $root (@$roots) {
$root->autoExpand(true); # recursive expansion
print Dumper($root); # a structure with all descendants
}
|