diff --git a/src/masoniteorm/models/Model.py b/src/masoniteorm/models/Model.py index bc9b0ff1..052f08ee 100644 --- a/src/masoniteorm/models/Model.py +++ b/src/masoniteorm/models/Model.py @@ -810,6 +810,23 @@ def method(*args, **kwargs): return None + def only(self, attributes: list) -> dict: + if isinstance(attributes, str): + attributes = [attributes] + results: dict[str, Any] = {} + for attribute in attributes: + if " as " in attribute: + attribute, alias = attribute.split(" as ") + alias = alias.strip() + attribute = attribute.strip() + else: + alias = attribute.strip() + attribute = attribute.strip() + + results[alias] = self.get_raw_attribute(attribute) + + return results + def __setattr__(self, attribute, value): if hasattr(self, "set_" + attribute + "_attribute"): method = getattr(self, "set_" + attribute + "_attribute") diff --git a/tests/models/test_models.py b/tests/models/test_models.py index 520244fc..353884de 100644 --- a/tests/models/test_models.py +++ b/tests/models/test_models.py @@ -186,6 +186,15 @@ def test_force_update_on_model_class(self): self.assertIn("username", sql) self.assertIn("name", sql) + def test_only_method(self): + model = ModelTestForced.hydrate( + {"id": 1, "username": "joe", "name": "Joe", "admin": True} + ) + + + self.assertEquals({"username": "joe"}, model.only("username")) + self.assertEquals({"username": "joe"}, model.only(["username"])) + def test_model_update_without_changes_at_all(self): model = ModelTest.hydrate( {"id": 1, "username": "joe", "name": "Joe", "admin": True}