Re: Beginner many-to-many problems
[prev]
[thread]
[next]
[Date index for 2004/07/13]
On Mon, Jul 12, 2004 at 12:23:15PM -0400, Jesse Sheidlower wrote:
> > >> Second, I'd like to add a citation with accompanying subjects,
> > >> preferably in one shot.
> Is it the multiple addition that I would have to write myself? What
> would be the way of adding a single subject to an existing citation
> object? Again, the basic setup is that there's a many-to-many
> correspondence between my Citation class and my Subject class, looking
> like this:
> package Citations;
> use base 'Citations::DBI';
> __PACKAGE__->set_up_table("citation");
> __PACKAGE__->has_many(subject => [ CitationSubject => 'subject_id' ]);
Your best bet is probably to override create() something along these
lines: (Adapted to Film / Star / Role as I can't think in your schema yet)
sub Film::create {
my ($class, $data) = @_;
my $star_names = delete $data->{stars};
my @stars = map Star->find_or_create({ name => $_ }) @$star_names;
my $film = $class->SUPER::create($data);
$film->add_to_roles(star => $_) foreach @stars;
return $film;
}
(you'll need to add sensible error checking etc...)
Then you can do:
Film->create({
title => "Heaven",
runtime => 93,
rating => 15,
stars => [ "Giovanni Ribisi", "Cate Blanchett" ]
});
Tony