[CDBI] delete from lookup table

Bill Moseley moseley at hank.org
Wed Oct 26 21:47:00 BST 2005

On Tue, Oct 25, 2005 at 04:57:51PM +0200, WulfDirk.Leuschner at sanofi-aventis.com 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 at hank.org

More information about the ClassDBI mailing list