From 6cedb8727aebb46089cc901dae583a5813e05692 Mon Sep 17 00:00:00 2001 From: Joe Mancuso Date: Sat, 23 Nov 2024 08:41:47 -0500 Subject: [PATCH] wip --- src/masoniteorm/models/Model.py | 5 ++++- .../models/relationships/new/HasMany.py | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/masoniteorm/models/Model.py b/src/masoniteorm/models/Model.py index 8b1444c7..caab3742 100644 --- a/src/masoniteorm/models/Model.py +++ b/src/masoniteorm/models/Model.py @@ -1193,6 +1193,8 @@ def __init__(self, relationship): def __getattr__(self, name): """ Delegate attribute access to the related model instance. + + this is returned when you do model.relationship.name """ related_instance = self.relationship.get() if related_instance: @@ -1202,9 +1204,10 @@ def __getattr__(self, name): def __call__(self): """ Make the relationship callable to return the relationship instance. + this is returned when you do model.relationship() """ print("Calling relationship") - return self.relationship.apply_query() + return self.relationship # def __repr__(self): # return repr(self.relationship) \ No newline at end of file diff --git a/src/masoniteorm/models/relationships/new/HasMany.py b/src/masoniteorm/models/relationships/new/HasMany.py index 48b130dc..ae8803f0 100644 --- a/src/masoniteorm/models/relationships/new/HasMany.py +++ b/src/masoniteorm/models/relationships/new/HasMany.py @@ -23,8 +23,8 @@ def __call__(self): print("calling") return self.relationship.apply_query().get() - def where(self, key): - return self.related_model.where(key, value) + # def where(self, key): + # return self.related_model.where(key, value) def apply_query(self): """Apply the query and return a dictionary to be hydrated @@ -37,4 +37,15 @@ def apply_query(self): dict -- A dictionary of data which will be hydrated. """ print("applying query has many") - return self.related_model.where(self.foreign_key, getattr(self.parent, self.foreign_key)) \ No newline at end of file + return self.related_model.where(self.foreign_key, getattr(self.parent, self.foreign_key)) + + def __getattr__(self, name, *args, **kwargs): + """ + this is called when accesssing query builder methods on the relationship class + + this is returned when you do model.relationship().where(...) + """ + related_instance = self.apply_query() + if related_instance: + return getattr(related_instance, name) + raise AttributeError(f"{self.__class__.__name__} has no attribute '{name}'") \ No newline at end of file