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])