[Dbix-class] prefetching and many_to_many

Stanis Trendelenburg stanis.trendelenburg at pluto.uni-freiburg.de
Fri Aug 11 17:42:05 CEST 2006


Matt S Trout wrote:
> In a word, "yes". It's a limitation of the current implementation; patches 
> welcome or one of the existing devs will get round to it when we have tuits.

OK, thanks for the clarification.

After reading some more of the documentation and looking at
Relationship/ManyToMany.pm I see why this is the case.
The many_to_many accessor returns a resultset created by

  $self->search_related($rel)->search_related($f_rel)

where $rel is the has_many relation from the original class to the
mapping class, and $f_rel the belongs_to relation from the mapping class
to the wanted class.
If I understand this correctly, this new resultset has no information
about the current object (like prefetched values).

What do you think of the following patch to the many_to_many accessor:
When the accessor is called in list context without arguments, return
the objects directly (which will use the prefetched values) instead
of returning the resultset from search_related().

This way we get the benefit of prefetching for many-to-many
relationships for one very common usage case.

--- ManyToMany.pm.orig  2006-08-11 15:02:41.000000000 +0200
+++ ManyToMany.pm   2006-08-11 16:48:57.000000000 +0200
@@ -16,6 +16,9 @@

     *{"${class}::${meth}"} = sub {
       my $self = shift;
+      if (wantarray && !@_ && !$rel_attrs) {
+        return map { $_->$f_rel } $self->$rel;
+      }
       my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
       $self->search_related($rel)->search_related(
         $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }



More information about the Dbix-class mailing list