[Dbix-class] Unnecessary re-fetching via belongs_to relationships?
Tim Watson
tiwatson at gmail.com
Thu Jun 29 00:22:21 CEST 2006
Does $child have a parentid in its table to relate it to the parent ?
Couldn't you just use:
$child->parentid
Or do you want to use other values from the parent table in the loop?
-timw
On 6/28/06, Mark Blythe <list at markblythe.com> wrote:
> 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__->table('parent');
> __PACKAGE__->add_columns('parent_id');
> __PACKAGE__->set_primary_key('parent_id');
>
> __PACKAGE__->has_many(children => 'MyApp::Schema::Main::Child',
> 'parent_id');
>
>
> package MyApp::Schema::Main::Child;
>
> __PACKAGE__->table('child');
> __PACKAGE__->add_columns('child_id');
> __PACKAGE__->set_primary_key('child_id');
>
> __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
> accessible.
>
> Thanks
>
> _______________________________________________
> List: http://lists.rawmode.org/cgi-bin/mailman/listinfo/dbix-class
> Wiki: http://dbix-class.shadowcatsystems.co.uk/
> IRC: irc.perl.org#dbix-class
> SVN: http://dev.catalyst.perl.org/repos/bast/trunk/DBIx-Class/
> Searchable Archive:
> http://www.mail-archive.com/[email protected]/
>
--
Tim Watson
Solution Scripts
More information about the Dbix-class
mailing list