@@ -37,6 +37,14 @@ class Employee(Base):
37
37
id = Column(UUID , primary_key = True )
38
38
name = Column(String, nullable = False )
39
39
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' )
40
48
```
41
49
42
50
Next, decorate a type with ` strawberry_sqlalchemy_mapper.type() `
@@ -55,14 +63,28 @@ class Employee:
55
63
__exclude__ = [" password_hash" ]
56
64
57
65
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
+
58
77
# context is expected to have an instance of StrawberrySQLAlchemyLoader
59
78
class CustomGraphQLView (GraphQLView ):
60
79
def get_context (self ):
61
80
return {
62
- " sqlalchemy_loader" : StrawberrySQLAlchemyLoader(),
81
+ " sqlalchemy_loader" : StrawberrySQLAlchemyLoader(bind = YOUR_SESSION ),
63
82
}
64
83
65
84
# 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)
66
88
strawberry_sqlalchemy_mapper.finalize()
67
89
# only needed if you have polymorphic types
68
90
additional_types = list (strawberry_sqlalchemy_mapper.mapped_types.values())
@@ -72,6 +94,29 @@ schema = strawberry.Schema(
72
94
extensions = extensions,
73
95
types = additional_types,
74
96
)
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
+ """
75
120
```
76
121
77
122
0 commit comments