Skip to content

Commit dd10748

Browse files
committed
Add more thorough example
1 parent aa4097b commit dd10748

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

README.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ class Employee(Base):
3737
id = Column(UUID, primary_key=True)
3838
name = Column(String, nullable=False)
3939
password_hash = Column(String, nullable=False)
40+
department_id = Column(UUID, ForeignKey('department.id'))
41+
department = relationship('Department', back_populates='employees')
42+
43+
class Department(Base):
44+
__tablename__ = "department"
45+
id = Column(UUID, primary_key=True)
46+
name = Column(String, nullable=False)
47+
employees = relationship('Employee', back_populates='department')
4048
```
4149

4250
Next, decorate a type with `strawberry_sqlalchemy_mapper.type()`
@@ -55,14 +63,28 @@ class Employee:
5563
__exclude__ = ["password_hash"]
5664

5765

66+
@strawberry_sqlalchemy_mapper.type(models.Department)
67+
class Department:
68+
pass
69+
70+
71+
class Query:
72+
@strawberry.field
73+
def departments(self):
74+
return db.session.scalars(select(models.Department)).all()
75+
76+
5877
# context is expected to have an instance of StrawberrySQLAlchemyLoader
5978
class CustomGraphQLView(GraphQLView):
6079
def get_context(self):
6180
return {
62-
"sqlalchemy_loader": StrawberrySQLAlchemyLoader(),
81+
"sqlalchemy_loader": StrawberrySQLAlchemyLoader(bind=YOUR_SESSION),
6382
}
6483

6584
# call finalize() before using the schema:
85+
# (note that models that are related to models that are in the schema
86+
# are automatically mapped at this stage -- e.g., Department is mapped
87+
# because employee.department is a relationshp to Department)
6688
strawberry_sqlalchemy_mapper.finalize()
6789
# only needed if you have polymorphic types
6890
additional_types = list(strawberry_sqlalchemy_mapper.mapped_types.values())
@@ -72,6 +94,29 @@ schema = strawberry.Schema(
7294
extensions=extensions,
7395
types=additional_types,
7496
)
97+
98+
# You can now query, e.g.:
99+
"""
100+
query {
101+
departments {
102+
id
103+
name
104+
employees {
105+
edge {
106+
node {
107+
id
108+
name
109+
department {
110+
# Just an example of nested relationships
111+
id
112+
name
113+
}
114+
}
115+
}
116+
}
117+
}
118+
}
119+
"""
75120
```
76121

77122

0 commit comments

Comments
 (0)