[Dbix-class] Avoiding foreign key constraint on a relationship

Rob Kinyon rob.kinyon at gmail.com
Sun Mar 1 16:45:07 GMT 2009


On Sun, Mar 1, 2009 at 11:37, W Snyder <wsnyder at wsnyder.org> wrote:
>
> One of my DBIx::Class table classes has:
>
> __PACKAGE__->table("adjacents");
> __PACKAGE__->add_columns(
>    "child_id"          => { ... },
>    "parent_id"         => { ... },
> );
> __PACKAGE__->set_primary_key("child_id");
> __PACKAGE__->base_has_one(parent_string => 'X::Schema::String',
>        {'foreign.object_id' => 'self.parent_id'});
>
> This results in the (MySQL) creation commands
>
> CREATE TABLE `adjacents` (
>  ...
>  CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`)
>       REFERENCES `strings` (`object_id`)
>
> The problem is I want to eliminate this constraint from the
> SQL creation but not from what DBIx accessors are made.
> (Because the constraint is sometimes violated, and I need to
> index it in a special way).
>
> How do I create a relationship so I can call
> $object->parent_string, but not have a CONSTRAINT added to
> the database schema?

Why not build it by hand? That way, you can handle the times when it
is violated. In your Row class, add the something like the following:

sub parent_string {
    my $self = shift;

    my @rows = $self->result_source->schema->result_set('strings')->search({
        object_id => $self->parent_id,
    });

    if ( @rows ) {
        die "Too many rows returned!\n" if @rows > 1;
        return $rows[0];
    }

    return;
}

Rob



More information about the DBIx-Class mailing list