[Dbix-class] prefetching and many_to_many

Matt S Trout dbix-class at trout.me.uk
Fri Aug 11 01:07:08 CEST 2006


Stanis Trendelenburg wrote:
> Hi List,
> 
> I am playing around with the many-to-many relationship example from
> DBIx::Class::Manual::Cookbook (user <-> address, via user_address
> mapping table). So far everything works as expected.
> 
> Now I'm trying to to fetch a user and also prefetch all his addresses.
> After some trial and error I found out that this:
> 
>   my $user = $user_rs->find( 1,
>    { prefetch => { user_address => address } }
>   );
> 
> produces the correct SQL (via DBIC_TRACE):
> 
>   SELECT me.id, me.name, user_address.user, user_address.address,
>          address.id, address.street
>   FROM user me
>   LEFT JOIN user_address user_address ON ( user_address.user = me.id )
>   JOIN address address ON ( address.id = user_address.address )
>   WHERE ( ( me.id = ? ) ) ORDER BY user_address.user: '1'
> 
> Now when I want to access the address objects linke this:
> 
>   foreach ( $user->addresses ) { print $_->street };
> 
> it prints the correct results, but every row in the address table is
> fetched from the database again:
> 
>   SELECT address.id, address.street
>   FROM user_address me
>   JOIN address address ON ( address.id = me.address )
>   WHERE ( me.user = ? ): '1'
> 
> To actually use the prefetched values, I have to access the related
> objects via the mapper object:
> 
>   foreach ( $user->user_address ) { print $_->address->street };
> 
> (No SQL generated)
> 
> What is the difference between the two methods? I find the 1st one
> (using the many-to-many accessor) to be more intuitive, but somehow it
> does not seem to "know" about the prefetched values?

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.



More information about the Dbix-class mailing list