Re: Duplicate constraint on many-to-many

[prev] [thread] [next] [Date index for 2005/06/25]

From: Bill Moseley
Subject: Re: Duplicate constraint on many-to-many
Date: 15:15 on 25 Jun 2005
On Sat, Jun 25, 2005 at 07:04:01AM -0400, Michael Peters wrote:
> You could do probably just do something like this:
> 
>   my $role = Role->find_or_create({ name => 'Admin' });
>   my $pr = PersonRole->find_or_create({
>     role   => $role,
>     person => $person,
>   );
> 

That makes sense.  I got caught up trying to use the add_to_roles()
method cdbi had nicely created for me.  I can replace it with one
that does add_to_roles, as Ask also suggested.

So:

    package DB::Person;

    # Don't use CDBI's methods for roles() and add_to_roles()
    # __PACKAGE__->has_many( roles => [ 'DB::PersonRole' => 'role' ] );

    sub add_to_roles {
        my ( $self, $data ) = @_;
        $data->{person} = $self->id;
        DB::PersonRole->find_or_create( $data );
    }

    __PACKAGE__->has_many(_role_refs => 'DB::PersonRole' );
    sub roles {
        my $self = shift;
        return map $_->role, $self->_role_refs;
    }


There was discussion on the Catalyst list about trying to
automatically create the methods for these simple many-to-many tables
in CDBI::Loader.  Seems like the common case for mapping tables is to
not allow duplicates, and that that might be nice if CDBI::Loader
used find_or_create() when creating the add_to_* methods.  Although,
I guess some may want to catch that as an error, though.







        -- 
        Bill Moseley
moseley@xxxx.xxx

Duplicate constraint on many-to-many
Bill Moseley 00:45 on 25 Jun 2005

Re: Duplicate constraint on many-to-many
Michael Peters 11:04 on 25 Jun 2005

Re: Duplicate constraint on many-to-many
Bill Moseley 15:15 on 25 Jun 2005

Generated at 16:37 on 28 Jul 2005 by mariachi v0.52