Re: No way to instantiate two related CDBI classes at once, is there?

[prev] [thread] [next] [Date index for 2004/08/09]

From: Perrin Harkins
Subject: Re: No way to instantiate two related CDBI classes at once, is there?
Date: 15:55 on 09 Aug 2004
It can be done.

package Foo;

__PACKAGE__->set_sql(get_both => qq{
    SELECT foo.id, foo.other, bar.id, bar.other
    FROM __TABLE__
    WHERE foo.a = ?
};

sub retrieve_with_bar {
    my ($class, $id) = @_;
    my $sth = $class->sq_get_both();
    $sth->execute($id);
    my $row = $sth->fetchrow_arrayref();
    my $foo = Foo->construct($row->[0,1]);
    my $bar = Bar->construct($row->[2,3]);
    $foo->{'_bar_object'} = $bar;
    return $foo;
}

sub bar {
    my $self = shift;
    return $self->{'_bar_object'};
}

If you read through the Class::DBI::Relationship::MightHave source, you
can see how to make it store the object just like the normal might_have
method does, and avoid the need to create your own accessor.  That would
certainly violate encapsulation, and my example here has
retrieve_with_bar tightly coupled to the SQL statement, but it should
work.

- Perrin

Re: No way to instantiate two related CDBI classes at once, is there?
Perrin Harkins 15:55 on 09 Aug 2004

Generated at 11:34 on 01 Dec 2004 by mariachi v0.52