Check relationship declarations more consistently
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
index cbc4484..f6ce3a5 100644 (file)
@@ -25,9 +25,6 @@ sub belongs_to {
 
   # no join condition or just a column name
   if (!ref $cond) {
-    $class->ensure_class_loaded($f_class);
-
-    my $pri = $f_class->result_source_instance->_single_pri_col_or_die;
 
     my ($f_key, $guess);
     if (defined $cond and length $cond) {
@@ -43,6 +40,19 @@ sub belongs_to {
       "No such column '$f_key' declared yet on ${class} ($guess)"
     )  unless $class->has_column($f_key);
 
+    $class->ensure_class_loaded($f_class);
+    my $f_rsrc = try {
+      $f_class->result_source_instance;
+    }
+    catch {
+      $class->throw_exception(
+        "Foreign class '$f_class' does not seem to be a Result class "
+      . "(or it simply did not load entirely due to a circular relation chain)"
+      );
+    };
+
+    my $pri = $f_rsrc->_single_pri_col_or_die;
+
     $cond = { "foreign.${pri}" => "self.${f_key}" };
 
   }
@@ -50,6 +60,8 @@ sub belongs_to {
   else {
     if (ref $cond eq 'HASH') { # ARRAY is also valid
       my $cond_rel;
+      # FIXME This loop is ridiculously incomplete and dangerous
+      # staving off changes until implmentation of the swindon consensus
       for (keys %$cond) {
         if (m/\./) { # Explicit join condition
           $cond_rel = $cond;
@@ -79,6 +91,7 @@ sub belongs_to {
   $class->add_relationship($rel, $f_class,
     $cond,
     {
+      is_depends_on => 1,
       accessor => $acc_type,
       $fk_columns ? ( fk_columns => $fk_columns ) : (),
       %{$attrs || {}}