22
33## Multiple Relationships to the Same Model
44
5- We've seen how tables are related to each other via a single relationship attribute but what if more than
6- one attribute links to the same table?
5+ We've seen how tables are related to each other via a single relationship attribute but what if more than
6+ one attribute links to the same table?
77
88What if you have a ` User ` model and an ` Address ` model and would like
9- to have ` User.home_address ` and ` User.work_address ` relationships to the same
9+ to have ` User.home_address ` and ` User.work_address ` relationships to the same
1010` Address ` model? In SQL you do this by creating a table alias using ` AS ` like this:
1111
1212```
13- SELECT *
14- FROM user
13+ SELECT *
14+ FROM user
1515JOIN address AS home_address_alias
1616 ON user.home_address_id == home_address_alias.id
1717JOIN address AS work_address_alias
1818 ON user.work_address_id == work_address_alias.id
1919```
2020
21- The aliases we create are ` home_address_alias ` and ` work_address_alias ` . You can think of them
21+ The aliases we create are ` home_address_alias ` and ` work_address_alias ` . You can think of them
2222as a view to the same underlying ` address ` table.
2323
2424We can this with ** SQLModel** and ** SQLAlchemy** using ` sqlalchemy.orm.aliased `
@@ -45,7 +45,7 @@ winter and summer teams or on the same team for both seasons.
4545
4646///
4747
48- The ` sa_relationship_kwargs={"primaryjoin": ...} ` is a new bit of info we need for ** SQLAlchemy** to
48+ The ` sa_relationship_kwargs={"primaryjoin": ...} ` is a new bit of info we need for ** SQLAlchemy** to
4949figure out which SQL join we should use depending on which attribute is in our query.
5050
5151## Creating Heros
@@ -71,7 +71,7 @@ team to the `winter_team` and `summer_team` attributes:
7171///
7272## Searching for Heros
7373
74- Querying ` Heros ` based on the winter or summer teams adds a bit of complication. We need to create the
74+ Querying ` Heros ` based on the winter or summer teams adds a bit of complication. We need to create the
7575alias and we also need to be a bit more explicit in how we tell ** SQLAlchemy** to join the ` hero ` and ` team ` tables.
7676
7777We create the alias using ` sqlalchemy.orm.aliased ` function and use the alias in the ` where ` function. We also
0 commit comments