Added patch from Schwern to allow cdbi compat to infer the has_many from a has_a
Jess Robinson [Wed, 14 Mar 2007 15:02:44 +0000 (15:02 +0000)]
lib/DBIx/Class/CDBICompat/HasMany.pm
t/cdbi-t/09-has_many.t
t/testlib/OtherThing.pm [new file with mode: 0644]
t/testlib/Thing.pm [new file with mode: 0644]

index 382b9cb..6438e43 100644 (file)
@@ -20,6 +20,12 @@ sub has_many {
     $args->{cascade_delete} = 0;
   }
 
+  if( !$f_key and !@f_method ) {
+      my $f_source = $f_class->result_source_instance;
+      ($f_key) = grep { $f_source->relationship_info($_)->{class} eq $class }
+                      $f_source->relationships;
+  }
+
   $class->next::method($rel, $f_class, $f_key, $args);
 
   if (@f_method) {
index 2af5485..28fa55e 100644 (file)
@@ -6,15 +6,15 @@ BEGIN {
   eval "use DBIx::Class::CDBICompat;";
   plan skip_all => 'Class::Trigger and DBIx::ContextualFetch required' if $@;
   eval "use DBD::SQLite";
-  plan $@ ? (skip_all => 'needs DBD::SQLite for testing') : (tests => 30);
+  plan $@ ? (skip_all => 'needs DBD::SQLite for testing') : (tests => 31);
 }
 
 
 use lib 't/testlib';
 use Film;
 use Actor;
-Film->has_many(actors => Actor => 'Film', { order_by => 'name' });
 Actor->has_a(Film => 'Film');
+Film->has_many(actors => 'Actor', { order_by => 'name' });
 is(Actor->primary_column, 'id', "Actor primary OK");
 
 ok(Actor->can('Salary'), "Actor table set-up OK");
@@ -110,3 +110,18 @@ ok $@, $@;
 
 is($as->Name, 'Arnold Schwarzenegger', "Arnie's still Arnie");
 
+
+# Test infering of the foreign key of a has_many from an existing has_a
+{
+    use Thing;
+    use OtherThing;
+
+    Thing->has_a(that_thing => "OtherThing");
+    OtherThing->has_many(things => "Thing");
+
+    my $other_thing = OtherThing->create({ id => 1 });
+    Thing->create({ id => 1, that_thing => $other_thing });
+    Thing->create({ id => 2, that_thing => $other_thing });
+
+    is_deeply [sort map { $_->id } $other_thing->things], [1,2];
+}
diff --git a/t/testlib/OtherThing.pm b/t/testlib/OtherThing.pm
new file mode 100644 (file)
index 0000000..08c31ba
--- /dev/null
@@ -0,0 +1,11 @@
+package OtherThing;
+use base 'DBIx::Class::Test::SQLite';
+
+OtherThing->set_table("other_thing");
+OtherThing->columns(All => qw(id));
+
+sub create_sql {
+    return qq{
+        id              INTEGER
+    };
+}
diff --git a/t/testlib/Thing.pm b/t/testlib/Thing.pm
new file mode 100644 (file)
index 0000000..d71e22a
--- /dev/null
@@ -0,0 +1,14 @@
+package Thing;
+use base 'DBIx::Class::Test::SQLite';
+
+Thing->set_table("thing");
+Thing->columns(All => qw(id that_thing));
+
+sub create_sql {
+    return qq{
+        id              INTEGER,
+        that_thing      INTEGER
+    };
+}
+
+1;