Search code examples
perlmany-to-manydbix-class

Setting up a Many-to-Many relation of a table with itself with DBIx::Class


I am porting an application from Class::DBI to DBIx::Class and need help. I have a table T with a primary key tid and another table ChildT that relates a row of T to multiple (child) rows of T itself. How can I setup the relations between T and ChildT so that I can find all children of an instance of T. Here are the stripped down versions of these two tables:

T: (id, name);
ChildT: (rowid, tid, childid)

tid and childid both reference the id column of T.

Thanks!


Solution

  • I am answering my own question.

    The DBIx::Class::Relationship docs explain this clearly enough. In the ChildT Class define a belongs_to relationship to T using the foreign key childid:

    __PACKAGE__->belongs_to(parent => 'App::Schema::Result::T', 'childid');
    

    In the T Class define a has_many and a many_to_many relation with the ChildT class:

    __PACKAGE__->has_many(childrecords => 'App::Schema::Result::ChildT', 'tid');
    __PACKAGE__->many_to_many(children => 'childrecords', 'parent');
    

    With this $t->children gives all child records of any instance of T.