[CDBI] Has Many Problem

Oliver Jeeves oj at defuturo.co.uk
Thu Nov 16 17:02:01 GMT 2006


James Hargreaves wrote:
> Hi everyone!
> 
> I have two tables called fixtures and teams. A Fixture has a home_team
> and an away_team and hence:
> 
> has_a(home_team => 'MyPackage::Team');
> has_a(away_team => 'MyPackage::Team');
> 
> Hence a team has a list of fixtures:
> 
> has_many(fixtures => 'MyPackage::Fixture');
> 
> But this only returns the HOME fixtures. So I changed this to:
> 
> has_many(home_fixtures => 'MyPackage::Fixture', 'home_team');
> has_many(away_fixtures => 'MyPackage::Fixture', 'away_team');
> 
> sub fixtures
> { my $s = shift;
>  my @home_fixtures = $s->home_fixtures;
>  my @away_fixtures = $s->away_fixtures;
>  return ( @home_fixtures, @away_fixtures );
> }
> 
> Which returns what I want, if in a rather naff way! However, I have
> some fixtures where the same team is entered for both home_team and
> away_team fields (for when the opposition is T.B.C). In this case the
> fixture is returned twice!
> 
> Is there an easy way around this other than modifying my fixtures sub?
> I note that the following causes an error:
> 
> has_many(fixtures => 'MyPackage::Fixture', 'home_team', 'away_team');
> 
> This seems like a reasonable syntax for this situation? Though to be
> honest I would have thought the standard syntax would return the
> result set I want? The addition of a foreign key as the third
> parameter keys would then be used to select only home/away fixtures.
> 
> Any help would be appreciated!
> 
> Thanks
> Jay
> 

CDBI is certainly not without its problems (cue MST), but I don't
consider anything you've mentioned to actually be a problem.

Given two relationships, I think it's a reasonable assumption that a
user of the class would only want the results of one of them at a time,
simply because there are two seperate relationships, not one.

The solution to your problem, is to re-write your fixtures sub. I'd do
it like this:

sub fixtures
{
	my $self = shift;
	my %fixtures = map {$_ => 1}
		($self->home_fixtures, $self->away_fixtures);
	
	return keys %fixtures;
}

That's just off the top of my head, I haven't tested it.

-Oli

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: OpenPGP digital signature
Url : http://lists.digitalcraftsmen.net/pipermail/classdbi/attachments/20061116/0441c2bb/signature.pgp


More information about the ClassDBI mailing list