Re: [CDBI] delete from lookup table

[prev] [thread] [next] [Date index for 2005/10/26]

From: Bill Moseley
Subject: Re: [CDBI] delete from lookup table
Date: 20:47 on 26 Oct 2005
On Tue, Oct 25, 2005 at 04:57:51PM +0200, WulfDirk.Leuschner@xxxxxxxxxxxxxx.xxx wrote:
> Hi all,
> 
> is there a method that deletes entries from a lookup table in a
> many-to-many relationship? Some autogenerated method similar to
> 'add_to_<my_method> [which could be called
> 'remove_from_<my_method>]?

The use where I needed something like this is when updating, say, a
user form where there's collection of checkboxes for "Roles" which are
maintained in a many_to_many table.

I'll bet there's a better way (which is one reason I'm posting), but
here's some code.

BTW -- I'm not that clear on what the "mapping" array can hold -- seem
like it's always a one element array.


        # here, $class is "User" and $field->name is "roles"

        $meta = $class->meta_info('has_many')->{$field->name};


        # Grab the value from the form field
        my $value = $field->value;


        # Figure out which values to keep:

        my %keep = map { $_ => 1 } ref $value ? @$value : ( $value );


        # Get foreign class and its key that points to $class
        my $foreign_class = $meta->foreign_class;  # Mapping class
        my $foreign_key   = $meta->args->{foreign_key};
        my $related_key   = $meta->args->{mapping}->[0];



        # This limits to using a mapping table.  Hard to imagine an interface 
        # for adding a has_many without a mapping table, but it could be a table
        # of just columns id, name, f_key, I suppose.

        die "Failed to find related_key for field [$field] in class [$class]" unless $related_key;


        # Delete any items that are not to be kept

        for ( $foreign_class->search( { $foreign_key => $item } ) ) {
            $_->delete unless delete $keep{ $_->$related_key };
        }


        # Add in new ones
        $foreign_class->create( {
            $foreign_key => $item,
            $related_key => $_,
        } ) for keys %keep;




        -- 
        Bill Moseley
moseley@xxxx.xxx


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

Re: [CDBI] delete from lookup table
Peter Speltz 19:27 on 26 Oct 2005

Re: [CDBI] delete from lookup table
Bill Moseley 20:47 on 26 Oct 2005

Re: [CDBI] delete from lookup table
Peter Speltz 09:22 on 27 Oct 2005

Re: [CDBI] delete from lookup table
Bill Moseley 12:44 on 27 Oct 2005

Generated at 14:18 on 27 Oct 2005 by mariachi v0.52