[Dbix-class] many-to-many relationships

Matt S Trout dbix-class at trout.me.uk
Fri Sep 23 01:09:42 CEST 2005


On Thu, Sep 22, 2005 at 09:52:06PM +0100, Stig Brautaset wrote:
> Can you set up many-to-many relationships using DBIx::Class?

Can the system handle them? Yes. Does it do everything for you? Not yet.

Try something along the lines of the following -

package Base; # Should really use a schema, but hey, it's a quick example

use base qw/DBIx::Class/;

__PACKAGE__->load_components(qw/Core DB/);
__PACKAGE__->connection(...);

package Left;

use base qw/Base/;

__PACKAGE__->table('left');
__PACKAGE__->add_columns(qw/id left_stuff/);
__PACKAGE__->set_primary_key(qw/id/);
__PACKAGE__->has_many('mid' => 'Mid');

sub right {
  my ($self) = @_;
  return Right->search(
    { 'left.id' => $self->id },
    { join => { 'mid' => 'left' });
}

package Mid;

use base qw/Base/;

__PACKAGE__->table('mid');
__PACKAGE__->add_columns(qw/left right/);
__PACKAGE__->set_primary_key(qw/left right/);

__PACKAGE__->belongs_to('left' => 'Left');
__PACKAGE__->belongs_to('right' => 'Right');

package Right;

use base qw/Base/;

__PACKAGE__->table('right');
__PACKAGE__->add_columns(qw/id right_stuff/);
__PACKAGE__->set_primary_key(qw/id/);
__PACKAGE__->has_many('mid' => 'Mid');

sub left {
  my ($self) = @_;
  return Left->search(
    { 'right.id' => $self->id },
    { join => { 'mid' => 'right' });
}

-- 
     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