I'm not exactly sure how to go about doing this. I'm hoping that there is a CDBI way to do it; I'm thinking there probably isn't. How do you implement a many-to-many relationship of a table with itself?

Suppose I have a person class. (The SQL is for MySQL but should be obvious.)

package Person; use base 'MyCDBI'; __PACKAGE__->table('people'); __PACKAGE__->columns(All => qw(id name)); # CREATE TABLE people ( # id INT NOT NULL auto_increment, # name VARCHAR(255) NOT NULL, # PRIMARY KEY (id), # UNIQUE (name) # );

Now I want to record a tree of parents and children. I think the best way to do that is a table like so:

package Person::Relationship; use base 'MyCDBI'; __PACKAGE__->table('people_tree'); __PACKAGE__->columns(Primary => qw(parent child)); __PACKAGE__->has_a(parent => 'Person'); __PACKAGE__->has_a(child => 'Person'); # CREATE TABLE people_tree ( # parent int NOT NULL REFERENCES people, # child int NOT NULL REFERENCES people, # PRIMARY KEY (parent,child) # );

My question is: How do I add this relationship to the Person class in a sensible way? Ideally I could use something like

Person->has_many(children => [ Person::Relationship => child ]); Person->has_many(parents => [ Person::Relationship => parent ]);

But then CDBI doesn't know which column to use to identify "self". That is, I really need something like,

Person->has_many({ self_id => parent }, children => [ Person::Relation +ship => child ]); Person->has_many({ self_id => child }, parents => [ Person::Relationsh +ip => parent ]);

Any suggestions?


In reply to Class::DBI and a self-referencing many-to-many by jgallagher

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.