2ge has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I have question about using DBIx::Tree::NestedSet and using it. My aim is very easy, I have some categories and I'd like to store them in DB as tree. I found this nice module, I like it, but I run into problems and I don't know what to do further.
here is snippet what I wrote:
use strict; use warnings; use DBIx::Tree::NestedSet; use DBI; my $dbh = DBI->connect('DBI:mysql:test','root','') or die ($DBI::errstr); my $tree = DBIx::Tree::NestedSet->new( dbh => $dbh, no_locking => 1, table_name => 'db_tree' ); $dbh->do("DELETE from db_tree"); #we can't have more "top" categories, so we create "main" $tree->add_child_to_right( name=>'main' ); while (<DATA>) { chomp; my $hr; for my $item ( split '/' ) { $hr->{last_id} = $tree->add_child_to_right( name => $item, id => $hr->{last_id} ); } } print "\nThe Complete Tree:\n"; print $tree->create_report(); __DATA__ foo/bar bar/foo foo/bar/foo
Output is:
The Complete Tree: main (354)(1) foo (355)(2) bar (356)(3) bar (357)(2) foo (358)(3) foo (359)(2) bar (360)(3) foo (361)(4)
Ok, now problem - I don't want to have "foo/bar" and "foo/bar/foo" as separate paths, but instead only one: "foo/bar/foo" could anyone help me please ?

Replies are listed 'Best First'.
Re: duplicates in DB tree
by 2ge (Scribe) on Jun 14, 2005 at 13:31 UTC
    Hi

    after some tweaking I found answer for my question, here is one possible solution, it works only if categories are created from the scratch.
    use strict; use warnings; use DBIx::Tree::NestedSet; use DBI; use Data::Dumper; $Data::Dumper::Indent = 1; my $dbh = DBI->connect('DBI:mysql:test','root','') or die ($DBI::errstr); my $tree = DBIx::Tree::NestedSet->new( dbh => $dbh, no_locking => 1, table_name => 'db_tree' ); $dbh->do("DELETE from db_tree"); #we can't have more "top" categories, so we create "main" $tree->add_child_to_right( name=>'main' ); my %tree = (); while (<DATA>) { chomp; my $hr; $hr->{last_node_id} = 0; my $t = \%tree; for my $item ( split '/' ) { #if path doesn't exists in hash unless ( exists $t->{$item} ) { #add to db $hr->{last_id} = $tree->add_child_to_right( name => $item, id=>$hr->{last_node_id} ); #make data hash structure $t->{$item} = { 'node_id' => $hr->{last_id} } ; } $hr->{last_node_id} = $t->{$item}{node_id}; print $hr->{last_node_id}, "\n"; $t = \%{$t->{$item}}; } } print "\n", Dumper(\%tree), "\n"; print "\nThe Complete Tree:\n"; print $tree->create_report(); __DATA__ foo/bar bar/foo foo/bar/foo foo/bar/foo/bar/bar/foo foo/bar/bar/bar
    if the table categories is not created from scratch this will not work. So I have to find also answer to this question, anyone can help me :)
Re: duplicates in DB tree
by thcsoft (Monk) on Jun 14, 2005 at 13:21 UTC
    maybe Data::Dumper could be helpful.

    language is a virus from outer space.
      thc, very helpful answer, thanks :)