[CDBI] ChildOf

Matt S Trout dbix-class at trout.me.uk
Sun Sep 11 14:53:31 BST 2005


On Fri, Sep 09, 2005 at 05:09:35PM -0700, Kate Yoak wrote:
> > This sounds useful, but I don't quite understand from your
> > description how it
> > differs from a has_a relationship from the child to the parent
> > (other than it
> > allows you to specify the accessor name for the parent). What am
> > I missing?
> >
> > I implement similar parent/child relationships like so:
> >
> > Parent->columns('Primary' => qw/parent_id/);
> > Parent->has_many(children => Child);
> > Child->columns('Primary' => qw/child_id/);
> > Child->columns('Others => qw/parent_id/);
> > Child->has_a(parent_id => Parent);
> >
> > How does ChildOf simplify or improve on this?
> >
> > Thanks,
> > Ed
> >
> 
> Good point.  Forgot to explain.  The problem with has_a is that it takes
> your primary column, your object id (that you are probably using everywhere
> in urls, keys, etc) and turns it into a parent object.  That's not very nice
> from two perspectives:
> 
> #1.  I like my id where it is!  :-)  I mean, really - when I say <a
> href="/?a_id=<%$link->link_id%>"> I expect a number to show up. (I believe
> it actually will - because of stringify - but read on).
> 
> #2.  I don't want to go to the database for the parent just because I am
> accessing the child's id.
> 
> OK.  So #1 actually works as-is.  Unless you have a custom stringify, your
> $link->link_id in a string context should show up as a number.  but it does
> so by first going to the database , and then converting the result into the
> number (the #2 issue).  What's worse is - I may choose to override
> stringify - and break a completely independent module - that's not so good.

Yeah, we noticed this problem when building the relationship code for
dbix-class. If you don't ask for an accessor (type 'filter' for inflation)
it doesn't build one, so

my $foo_id = $obj->foo_id;

just returns the id. Then you'd do

my ($foo_obj) = $obj->search_related('foo_id');

If you wanted to have an accessor for the object but not on the column name,
then you could do

__PACKAGE__->add_relationship('foo', 'FooClass',
               { 'foreign.id' => 'self.foo_id' }, # join condition
               { accessor => 'single' });         # attrs

Then $obj->foo_id will return the id, but $obj->foo will function as an
accessor to the related object. A proposal for a Relationship::HasOne class
for DBIx::Class which provides a nicer interface was recently posted to the
dbix-class list - you might want to have a look at that for inspiration.

-- 
     Matt S Trout       Specialists in perl consulting, web development, and
  Technical Director    UNIX/Linux systems architecture and automation. Mail
Shadowcat Systems Ltd.  mst (at) shadowcatsystems.co.uk for more information

 + Help us build a better perl ORM: http://dbix-class.shadowcatsystems.co.uk/ +




More information about the ClassDBI mailing list