[Dbix-class] many to many self join?

Matt S Trout dbix-class at trout.me.uk
Tue Oct 18 19:47:10 CEST 2005


On Tue, Oct 18, 2005 at 06:27:39PM +0100, Richard Jolly wrote:
> Hello DBIx::Class,
> 
> I'm having difficulty with a many-to-many self join:
> 
> TABLE A
> - id
> 
> TABLE AA
> - id
> - parent_id
> - child_id

How about -

__PACKAGE__->has_many(
   'child_links', # relationship name
   'AA', # class of join table
   { 'foreign.parent_id' => 'self.id' }
 );

__PACKAGE__->has_many(
    'parent_links',
    'AA',
    { 'foreign.child_id' => 'self.id' } );
  );

sub children {
  my $self = shift;
  A->search(
    { 'parent_links.parent_id' => $self->id },
    { join => 'parent_links' },
  );
}

sub parents {
  my $self = shift;
  A->search(
    { 'child_links.child_id' => $self->id },
    { join => 'child_links' },
  );
}

> package AA;
> 
> __PACKAGE__->belongs_to(
>   'parent_id' => 'A',
>         );
> 
> __PACKAGE__->belongs_to(
>   'child_id' => 'A',
>         );

You won't need the belongs_to statements unless you want the ids inflated
to A objects.

-- 
     Matt S Trout       Specialists in perl consulting, web development, and
  Technical Director    UNIX/Linux systems architecture and automation. Mail
Shadowcat Systems Ltd.  mst (at) shadowcatsystems.co.uk for more information

 + Help us build a better perl ORM: http://dbix-class.shadowcatsystems.co.uk/ +



More information about the Dbix-class mailing list