[CDBI] Re: Many-to-many relationships of same type?

Edward J. Sabol sabol at alderaan.gsfc.nasa.gov
Tue Jun 19 18:40:26 BST 2007

Ciaran Hamilton wrote:
> I'm a newcomer to Class::DBI, and I'm having a problem - I need to
> implement a many-to-many relationship where the objects involved are
> both of the same type. The specific application is using data obtained
> from LiveJournal, where users can have other users as 'friends'. I
> can't seem to get this to work since it appears to use the first
> object of this type. This is basically what I have in the relevant
> files:
> __PACKAGE__->has_many(friends   => [ 'LJData::Friends' => 'friend' ]);

You need to use the three-argument version of has_many(). The third argument
allows you to explicitly specify the name of the foreign key. I remember
being confounded by this when I first started using Class::DBI many moons ago
and tried to set up my first many-to-many relationship. It's a shame the
Class::DBI documentation doesn't cover this aspect very well. The examples in
the documentation all assume the foreign key and the class have the same

Try this instead:

__PACKAGE__->has_many(friends => [ 'LJData::Friends' => 'friend' ] => 'userid');

I hope I got that right!


More information about the ClassDBI mailing list