[Dbix-class] Unnecessary re-fetching via belongs_to relationships?

Mark Blythe list at markblythe.com
Wed Jun 28 21:03:23 CEST 2006

I have a situation where I see many seemingly needless queries
happening.  This happens when I access a set of related child records
via a has_many relationship, and then reference that original parent
object via a belongs_to relationship from the children.  For each
child object, the parent object is being re-fetched from the database,
even though that child was originally fetched *through* the parent
object.  For example (incomplete class examples):

package MyApp::Schema::Main::Parent;


__PACKAGE__->has_many(children => 'MyApp::Schema::Main::Child', 'parent_id');

package MyApp::Schema::Main::Child;


 __PACKAGE__->belongs_to(parent => 'MyApp::Schema::Main::Parent', 'parent_id');

Now, somewhere else (via catalyst app):

my $parent = $c->model('Main::Parent')->find($parent_id);

foreach my $child ($parent->children()) {
    print "child: ", $child->child_id, " parent: ",
$child->parent->parent_id, "\n";

So every time through the loop, $child->parent->parent_id causes the
parent record to be re-fetched from the database (according to DBIC
debug output).

Is this expected behavior?  I do have a few unusual areas in my DBIC
setup which could be causing this issue, but I want to make sure this
isn't normal before I launch a grand debugging mission.  It doesn't
seem like it *should* be normal.

BTW, I know I could get around it by simply accessing
$parent->parent_id directly, but my real case is in some common
display code where I don't always have the parent separately


More information about the Dbix-class mailing list