[CDBI] Many to many help

William Ross will at spanner.org
Mon Aug 1 10:16:04 BST 2005


On 1 Aug 2005, at 09:38, Mike McKay wrote:

> I need some help with a Many to Many situation. I have two tables,  
> passenger and route, which are in a many to many relationship via a  
> PassengerRouteJoin table. I followed the perldoc for Class::DBI to  
> create the many to many relationship using inflation. But it  
> doesn't work. Here is basically what I am doing:
>
> PassengerRouteJoin->has_a(passenger => "Passenger");
> PassengerRouteJoin->has_a(route => "Route");
>
> Route->has_many(passengers => [ "PassengerRouteJoin" =>  
> 'passenger' ]);
> Passenger->has_many(routes => [ "PassengerRouteJoin" => 'route' ]);
>
> So then I try and do this:
>
> my $p = Passenger->create({surname => "Blah", first_name => "Foo"});
> my $r = Route->create({departure_point => "Lilongwe", destination  
> => "Likoma"});
>
> $p->add_to_routes({route => $r});

At the moment this won't work because Passenger has no routes() or  
add_to_routes() method: they're both in the PassengerRouteJoin class  
that declared the has_many method. There are a few ways around this:

1. You just spell it out:

     my $p = Passenger->create({surname => "Blah", first_name =>  
"Foo"});
     my $r = Route->create({departure_point => "Lilongwe",  
destination => "Likoma"});
     my $pr = PassengerRouteJoin->create({passenger => $p, route =>  
$r});

2. you use the mapping syntax to put the routes() method in the  
Passenger class where you want it:

     Passenger->has_many(routes => [ 'PassengerRouteJoin' => 'route' ]);

in which case $p->add_to_routes({...}) should work. Incidentally,  
don't create the route object before you pass it in: add_to_foo  
always calls create(), so you'll get duplicates.

3. But unless PassengerRouteJoin is a completely empty apart from the  
linking information, you'll probably end up writing a custom  
add_route method in the Passenger class that will look a lot like [1]  
above but with more going on. You could consider getting it over with  
now.

hth

will





More information about the ClassDBI mailing list