in reply to Class::DBI and a self-referencing many-to-many

Class::DBI supports what you are asking for here, but you have the syntax worng. Set up your relationships like this:
Person->has_many(children => [ Person::Relationship => child ], 'paren +t'); Person->has_many(parents => [ Person::Relationship => parent ], 'child +');
In my opinion though, it would be better to just add a single parent_id column to your person table and use a simple tree structure. Adding a separate table complicates some things.

Replies are listed 'Best First'.
Re^2: Class::DBI and a self-referencing many-to-many
by jgallagher (Pilgrim) on Sep 14, 2005 at 18:45 UTC
    I have a couple of questions. First, regarding that syntax. This means (if I understand CDBI correctly) that I need to use my classes as so:
    my $parent1 = Person->create({ name => 'P1' }); my $parent2 = Person->create({ name => 'P2' }); my $child = Person->create({ name => 'C1' }); # This seems like a cumbersome way to set up the relationships $child->add_to_parents({ parent => $parent1 }); $child->add_to_parents({ parent => $parent2 }); # Or, alternatively # $parent1->add_to_children({ child => $child }); # $parent2->add_to_children({ child => $child });

    Is there any way to sucessfully set those relationships when I'm constructing the objects?

    Also, I thought of adding a single parent_id column to the person table, but wouldn't that prevent a given person from having multiple parents?

      Your syntax for adding parents looks correct, or you could just call create() on your linking table directly. What is it that you don't like about it? Do you have an example of alternative syntax you'd like to use?

      You're right that my parent_id column idea would mean only a single parent. I was thinking of a tree in computer science terms, where a node can only have one parent. What you want is probably a directed graph rather than a tree.

        my $parent1 = Person->create({ name => 'P1' }); my $parent2 = Person->create({ name => 'P2' }); I guess I was hoping to say something like this:
        my $parent = Person->create({ name => 'P' }); my $child = Person->create({ name => 'C1', parent => $parent });
        But I can live without it. :-)