Repository navigation
Many to many relationship between a table and itself #545
Description
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn't find it.
- I searched the SQLModel documentation, with the integrated search.
- I already searched in Google "How to X in SQLModel" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to SQLModel but to Pydantic.
- I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
- I commit to help with one of those options 👆
Example Code
from typing import List, Optional
from sqlmodel import Field, Relationship, SQLModel
class Edge(SQLModel, table=True):
from_node_id: Optional[int] = Field(default=None, foreign_key="node.id", primary_key=True)
to_node_id: Optional[int] = Field(default=None, foreign_key="node.id", primary_key=True)
class Node(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
from_nodes: List["Node"] = Relationship(back_populates="to_nodes", link_model=Edge)
to_nodes: List["Node"] = Relationship(back_populates="from_nodes", link_model=Edge)Description
I want to be able to create a many to many relationship between a table and itself. In my example, I have a table Node and a table Edge which I'm using to represent a graph. I want the table Edge to work as a link table establishing a many to many relationship between the table Node and itself. Like that, I would be able to benefit from the SQLModel's lazy loading when querying the nodes and also get the in and out adjacency lists for each node very efficiently.
Please, let me know if it's already possible somehow.
Wanted Solution
The solution I am thinking about is to add a field parameter to the Relationship callable. Check out my wanted code.
Wanted Code
from typing import List, Optional
from sqlmodel import Field, Relationship, SQLModel
class Edge(SQLModel, table=True):
from_node_id: Optional[int] = Field(default=None, foreign_key="node.id", primary_key=True)
to_node_id: Optional[int] = Field(default=None, foreign_key="node.id", primary_key=True)
class Node(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
from_nodes: List["Node"] = Relationship(back_populates="to_nodes", link_model=Edge, field="to_node_id")
to_nodes: List["Node"] = Relationship(back_populates="from_nodes", link_model=Edge, field="from_node_id")Alternatives
I couldn't think about any decent alternative. Please, let me know if you have another idea.
Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.6
Python Version
Python 3.9.12
Additional Context
No response
Activity
daniil-berg commentedon Feb 15, 2023
What you can already do is set up relationships back-and-forth between the
NodeandEdgetables, such thatNodehas a list of all outgoing edges and a list of all incoming edges andEdgehas references to its "to"- and "from"-nodes.Here is an example:
The
foreign_keyskeyword argument is important. (See SQLAlchemy docs here.)This allows you to quite a few things already. To get adjacency lists however you will still need the additional "hop" via the related
edgeobjects.Here is a demo:
Output:
It would be really nice, if we could define a
to_nodesand afrom_nodesattribute onNodedirectly to avoid going via theEdgeinstances. But for this we need the association proxy from SQLAlchemy to work and I believe it is currently not supported in SQLModel. (At least I could not get it to work right now.)Support for a custom association proxy might be a worthwhile feature in the future, but should maybe not be high priority IMHO.
ClanEver commentedon Feb 17, 2023
Looks the same as this #89
christianholland commentedon Feb 23, 2023
Thanks @daniil-berg, your answer already helped to improve my understanding about advanced usage of relationships!
In your answer above you have solved the case (as you stated) that
every "Node" has a list of all outgoing edges and a list of all incoming edges.While this should also be true for my use case I need also that edges can have multiple incoming and outgoing nodes. Just think about a receipe where (simplified)
DoughandButtermake aCake.Dough,ButterandCakeareNodeinstances and the baking process is an instance of theEdgemodel. Of course at the same time you could use the nodeButteralso for a different bakingedge.Ideally, the
Edgemodel should also have additional fields (e.g. to stay with the baking analogy, the baking temperature).I tried to update your solution by setting in the
Edgemodel the relationshipsfrom_nodeandto_noteas aListbut this did not work unfortunately.jackiezhangmm commentedon Aug 21, 2023
Use "remote_side" in "sa_relationship_kwargs"
lurkinlegit commentedon Nov 21, 2023
I split the Edge class into two classes for better clarity.
Each Node has two separate relationships (out_edges and in_edges) to the Edge class. One for outgoing edges and the other for incoming edges.
I defined corresponding relationships (from_node and to_node) in the Edge class.
This way, you can still retrieve the incoming and outgoing edges for each node using the relationships defined in the Node class. The downside is that you have to query both relationships separately when retrieving the adjacency lists.
`
LordPhwa commentedon Jan 31, 2024
This seems to work for me for a self-referential many-to-many relationship with relationship attributes.