Deleting related objects

From ClassDBI

ourelva If you need to delete an object that is in a has_a or might_have relationship, there are a few things to keep in mind.

Given the following SQL tables:

 TableA (
    id integer primary key
    my_b integer foreign key references TableB
 );
 
 TableB (
    id integer primary key
 );


... and then in !ClassA.pm in perl....

 __PACKAGE__->has_a (my_b, 'ClassB')

If you wish to delete a record in !TableB which has a relationship in !TableA, it is necessary to perform the following steps to prevent potential problems with referential integrity:

   my $a = MyDBI::TableA->retrieve($id);
   my $b = $self->my_b;
   $self->my_b(undef);
   $self->update;  # save modifications to the database
   $b->delete;

This code could be added to !ClassA.pm and called as a method using the following:

 sub remove_b {
   my $self = shift;  #  $self is an object of ClassA
   my $b = $self->my_b;
   $self->my_b(undef);
   $self->update;  # save modifications to the database
   $b->delete;
 }

...somewhere in your code...

 my $a = MyDBI::ClassA->retrieve($id);
 $a->remove_b;

For more details, see the mailing list thread "Deleting an object on the other side of a has_a" from September 2004. This example also works for might_have relationships as well.