[Catalyst] How to get from
will trillich
will.trillich at serensoft.com
Sat Sep 18 16:00:20 GMT 2010
Short version: we're wondering how a method from inside the SCHEMA can
return other
objects besides the one that got passed in. That is, we have $obj
(with its own ID
number) but we want to FIND a different object -- same type, but with
a different
ID number. What's the mechanism for that, inside the schema package?
Long version:
We've got a schema defined for hierarchical groups:
MyApp::Schema::DB::Result::Group
__PACKAGE__->add_columns(
"id",
{ data_type => "INT", default_value => undef, is_nullable => 0, size => 11 },
"name",
{
data_type => "VARCHAR",
default_value => undef,
is_nullable => 0,
size => 90,
},
"parent",
{ data_type => "INT", default_value => undef, is_nullable => 1, size => 11 },
);
__PACKAGE__->set_primary_key("id");
__PACKAGE__->belongs_to( parent => 'MyApp::Schema::DB::Result::Group'
=> 'parent' );
__PACKAGE__->has_many( subgroups => 'MyApp::Schema::DB::Result::Group',
{ 'foreign.parent' => 'self.id' },
{ order_by => 'name' },
);
So when there's an ID number in "parent" the current group object has
a parent group
object. When there's no ID (or it's zero) then that's the top-level group in its
hierarchy.
Creating a method for the top-level group is simple:
sub top {
my $self = shift;
my $top = $self;
while ( $self = $self->parent ) {
$top = $self;
}
return $top;
}
If we're looking for a certain PARENT with a given ID, that's simple too:
sub specific_parent {
my $self = shift;
my $id = shift;
while( $self->id != $id ) {
return unless $self = $self->parent;
}
return $self;
}
But how do we go about creating a method to look for a specific group by ID
that may not be in the parent-chain?
sub specific_group {
my $self = shift;
my $id = shift;
return unless $self->some_manner_of_valid_id_check( $id );
return $self->BLACK_MAGIC_HERE->find( {id=>$id} );
}
So the real question is, how do we get from $self to ->find() ?
More information about the Catalyst
mailing list