@@ -19,28 +19,18 @@ def apply_query(self, builder, foreign_key_value=None, eager=None):
1919 def get_related (self , foreign , result , eager = None ):
2020 return self .apply_query (self .model_class , getattr (result , self .local_key )).first ()
2121
22-
2322 def __call__ (self , owner ):
24- """Fetch the related record when invoked ."""
23+ """Return a query builder for the relationship ."""
2524 related_model = self .model_class
26- related_model .owner = self
2725 self .owner = owner
26+
27+ # Get the foreign key value
2828 foreign_key_value = owner .__attributes__ .get (self .local_key )
2929 if not foreign_key_value :
30- print ("No foreign key value" )
31- return self
32-
33- self .owner = owner
34- # print("relationships", owner, owner._relationships)
35- if self .method and self .method in owner ._relationships :
36- return owner ._relationships [self .method ]
37- builder = self .apply_query (related_model .builder )
38- result = builder .first ()
39- self .owner = owner
40- result .__dict__ ['related' ] = self
41- return result
42-
30+ return related_model .builder .where_raw ("1 = 0" ) # Return empty query if no foreign key
31+
32+ # Return the query builder directly
33+ return self .apply_query (related_model .builder , foreign_key_value )
4334
4435 def add_relation (self , model_instance , result , relation_key = None ):
45- # if result is a collection, do a where
46- return model_instance .add_relation ({relation_key : result or None })
36+ return model_instance .add_relation ({relation_key : result or None })
0 commit comments