Re: [CDBI] Many to many help

[prev] [thread] [next] [Date index for 2005/08/01]

From: William Ross
Subject: Re: [CDBI] Many to many help
Date: 09:16 on 01 Aug 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


_______________________________________________
ClassDBI mailing list
ClassDBI@xxxxx.xxxxxxxxxxxxxxxx.xxx
http://lists.digitalcraftsmen.net/mailman/listinfo/classdbi

[CDBI] Many to many help
Mike McKay 08:38 on 01 Aug 2005

Re: [CDBI] Many to many help
William Ross 09:16 on 01 Aug 2005

Re: [CDBI] Many to many help
William Ross 11:03 on 01 Aug 2005

Re: [CDBI] Many to many help
Bill Moseley 16:42 on 01 Aug 2005

Generated at 21:01 on 07 Aug 2005 by mariachi v0.52