[Dbix-class] wishlist: "might_have_many"
Matt S Trout
dbix-class at trout.me.uk
Thu Apr 13 16:29:47 CEST 2006
Mike Rylander wrote:
> On 4/12/06, Mark Hedges <hedges at ucsd.edu> wrote:
>> I found that if I do a prefetch on a Foo RS to its have_many
>> Bar, but it doesn't have any Bars, I don't get the Foo at all.
>>
>> This is similar to a problem where if I do a prefetch from one
>> to another with a 1:1 relationship, but the other doesn't exist,
>> it does not work if I defined with has_one but it does work if I
>> defined if might_have.
>>
>> However there isn't a fix for a 1:N relationship. (Doesn't 1:N
>> imply that N could equal 0?) Instead I have to remember where
>> this drop might occur and I get no object, and I can't prefetch.
>>
>
> Sounds like has_many should use LEFT JOIN ... [he says, sniping from
> the sidelines having not looked at the code]
It does :) -
package # hide from PAUSE
DBIx::Class::Relationship::HasMany;
use strict;
use warnings;
sub has_many {
my ($class, $rel, $f_class, $cond, $attrs) = @_;
eval "require $f_class";
if ($@) {
$class->throw_exception($@) unless $@ =~ /Can't locate/;
}
unless (ref $cond) {
my ($pri, $too_many) = $class->primary_columns;
$class->throw_exception( "has_many can only infer join for a single primary
key; ${class} has more" )
if $too_many;
my ($f_key,$guess);
if (defined $cond && length $cond) {
$f_key = $cond;
$guess = "caller specified foreign key '$f_key'";
} else {
$class =~ /([^\:]+)$/;
$f_key = lc $1; # go ahead and guess; best we can do
$guess = "using our class name '$class' as foreign key";
}
my $f_class_loaded = eval { $f_class->columns };
$class->throw_exception("No such column ${f_key} on foreign class ${f_class}
($guess)")
if $f_class_loaded && !$f_class->has_column($f_key);
$cond = { "foreign.${f_key}" => "self.${pri}" };
}
$class->add_relationship($rel, $f_class, $cond,
{ accessor => 'multi',
join_type => 'LEFT',
cascade_delete => 1,
cascade_copy => 1,
%{$attrs||{}} } );
}
1;
--
Matt S Trout Offering custom development, consultancy and support
Technical Director contracts for Catalyst, DBIx::Class and BAST. Contact
Shadowcat Systems Ltd. mst (at) shadowcatsystems.co.uk for more information
+ Help us build a better perl ORM: http://dbix-class.shadowcatsystems.co.uk/ +
More information about the Dbix-class
mailing list