From ac4af49163dc64905e364ba4237bc756c7c060f0 Mon Sep 17 00:00:00 2001 From: Aleks Andrs <59065138+aleksanm@users.noreply.github.com> Date: Tue, 16 Jun 2026 20:39:03 +0300 Subject: [PATCH] fix: implement map_related for BelongsToMany eager loading (#12) Eager loading a BelongsToMany relationship onto a collection (Model.with_("rel").get()) raised NotImplementedError because BelongsToMany never overrode map_related. register_related already filters the related collection per-model, so map_related simply returns the result unchanged (matching HasOne). Adds a regression test asserting each parent keeps its own related set. Co-Authored-By: Claude Opus 4.8 --- src/masoniteorm/relationships/BelongsToMany.py | 3 +++ .../relationships/test_sqlite_relationships.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/masoniteorm/relationships/BelongsToMany.py b/src/masoniteorm/relationships/BelongsToMany.py index 2477be94..d6b1cf32 100644 --- a/src/masoniteorm/relationships/BelongsToMany.py +++ b/src/masoniteorm/relationships/BelongsToMany.py @@ -355,6 +355,9 @@ def relate(self, related_record): return result + def map_related(self, related_result): + return related_result + def register_related(self, key, model, collection): model.add_relation( { diff --git a/tests/sqlite/relationships/test_sqlite_relationships.py b/tests/sqlite/relationships/test_sqlite_relationships.py index 14fd2629..2cfe6214 100644 --- a/tests/sqlite/relationships/test_sqlite_relationships.py +++ b/tests/sqlite/relationships/test_sqlite_relationships.py @@ -184,3 +184,17 @@ def test_belongs_to_eager_many(self): store = Store.hydrate({"id": 2, "name": "Walmart"}) store = Store.with_("products").first() self.assertEqual(store.products.count(), 3) + + def test_belongs_to_eager_many_on_collection(self): + # Eager loading a BelongsToMany onto a collection (get) used to raise + # NotImplementedError because map_related was not implemented. See #12. + stores = Store.with_("products").get() + self.assertEqual(stores.count(), 2) + + products_by_store = { + store.id: sorted(product.id for product in store.products) + for store in stores + } + # Each store keeps its own related products rather than sharing one set. + self.assertEqual(products_by_store[1], [1, 2, 3]) + self.assertEqual(products_by_store[2], [4, 5, 6])