Note that there are some explanatory texts on larger screens.

plurals
  1. POPerl: DBIx::Class Beginner - Subsetting Relationships and Prefetching
    primarykey
    data
    text
    <p>Okay, I'm new to DBIx::Class. I have a one-to-many relationship set up, like so:</p> <pre><code>User -&gt; has_many -&gt; Addresses </code></pre> <p>Okay, good. I can do a query, and call it prefetching JOINed tables, like so:</p> <pre><code>Foo::DBIC-&gt;storage-&gt;debug(1); # output SQL to STDOUT my $user = Foo::DBIC-&gt;resultset('Users')-&gt;search({}, { prefetch =&gt; [ 'addresses' ], join =&gt; [ 'addresses' ], rows =&gt; 1 })-&gt;single; for my $address ($user-&gt;addresses-&gt;all) { say $address-&gt;zip_code; } </code></pre> <p>Two tables, one SQL query (verified via debug). All is well.</p> <p>Now, however, let's say I want to write an overload method or two in Foo::DBIC::Result::Users that returns a <em>subset</em> of addresses, based on certain criteria. Here's what I've added to the Users class:</p> <pre><code>sub home_addresses { my $self = shift; return $self-&gt;search_related('addresses', { address_type =&gt; 'home' }); } sub business_addresses { my $self = shift; return $self-&gt;search_related('addresses', { address_type =&gt; 'business' }); } </code></pre> <p>I can call these overloads like so, and they work:</p> <pre><code>for my $address ($user-&gt;home_addresses-&gt;all) { say $address-&gt;zip_code; } </code></pre> <p>However, this <em>ignores</em> the fact that I've prefetched my join, and it performs ADDITIONAL QUERIES (as if I've not prefetched and joined anything).</p> <p>So, my question is this: how do I define an overload method that returns a subset of a related table, but uses the already prefetched join? (just appending a WHERE clause to the prefetch)...</p> <p>My problem is that if I have a lot of the overloaded methods returning related table subsets, my query count can blow up; especially if I'm calling them from within a loop.</p> <p>I have reasons for doing this that are, of course, ugly. My real life schema is a lot, lot, lot messier than Users and Addresses, and I'm trying to abstract away ugly as best I can.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload