Title: Multiple many-to-many self referencing relationships · Issue #89 · fastapi/sqlmodel · GitHub
Open Graph Title: Multiple many-to-many self referencing relationships · Issue #89 · fastapi/sqlmodel
X Title: Multiple many-to-many self referencing relationships · Issue #89 · fastapi/sqlmodel
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...
Open Graph 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...
X 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 searc...
Opengraph URL: https://github.com/fastapi/sqlmodel/issues/89
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Multiple many-to-many self referencing relationships","articleBody":"### First Check\n\n- [X] I added a very descriptive title to this issue.\n- [X] I used the GitHub search to find a similar issue and didn't find it.\n- [X] I searched the SQLModel documentation, with the integrated search.\n- [X] I already searched in Google \"How to X in SQLModel\" and didn't find any information.\n- [X] I already read and followed all the tutorial in the docs and didn't find an answer.\n- [X] I already checked if it is not related to SQLModel but to [Pydantic](https://github.com/samuelcolvin/pydantic).\n- [X] I already checked if it is not related to SQLModel but to [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy).\n\n### Commit to Help\n\n- [X] I commit to help with one of those options 👆\n\n### Example Code\n\n```python\nfrom typing import List, Optional\r\n\r\nfrom sqlmodel import Field, Relationship, Session, SQLModel, create_engine\r\n\r\n\r\nclass UserLink(SQLModel, table=True):\r\n parent_id: Optional[int] = Field(\r\n default=None, foreign_key=\"user.id\", primary_key=True\r\n )\r\n child_id: Optional[int] = Field(\r\n default=None, foreign_key=\"user.id\", primary_key=True\r\n )\r\n\r\n\r\nclass User(SQLModel, table=True):\r\n id: int = Field(default=None, primary_key=True)\r\n parents: List[\"User\"] = Relationship(back_populates=\"children\", link_model=UserLink)\r\n children: List[\"User\"] = Relationship(back_populates=\"parents\", link_model=UserLink)\r\n\r\n\r\nsqlite_file_name = \"database.db\"\r\nsqlite_url = f\"sqlite:///{sqlite_file_name}\"\r\nengine = create_engine(sqlite_url, echo=True)\r\nSQLModel.metadata.create_all(engine)\r\n\r\n\r\nwith Session(engine) as session:\r\n user_1 = User(id=1)\r\n session.add(user_1)\r\n\r\n user_2 = User(id=2, parents=[user_1])\r\n session.add(user_2)\r\n\r\n session.commit()\r\n\r\n session.refresh(user_1)\r\n session.refresh(user_2)\r\n\r\n assert len(user_1.children) == 1\r\n assert len(user_1.parents) == 0\r\n\r\n assert len(user_2.children) == 0\r\n assert len(user_2.parents) == 1\n```\n\n\n### Description\n\nI am trying to create a model with multiple many-to-many relationships referencing self. See example code.\r\n\r\nMy code raises this error:\r\n```\r\nsqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.parents - there are multiple foreign key paths linking the tables via secondary table 'userlink'. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables\r\n```\r\n\r\nMy code is based on the many-to-many example in the [docs](https://sqlmodel.tiangolo.com/tutorial/many-to-many/create-models-with-link/).\r\n\r\nAs the error is coming from sqlalchemy it might also be an sqlalchemy issue but as it is raised by an example that is coming from the docs I think I might be using SQLmodel incorrectly.\r\n\r\nI did read the [sqlalchemy docs](https://docs.sqlalchemy.org/en/14/orm/basic_relationships.html#many-to-one) on many-to-many relationships but they did not help me.\r\n\r\n[This](https://stackoverflow.com/questions/9116924/how-can-i-achieve-a-self-referencing-many-to-many-relationship-on-the-sqlalchemy) issue on stackoverflow seems related but I cannot figure out how to apply it to my situation.\r\n\r\nQuestions:\r\n- Am I correct in the assumption that I need to use many-to-many relationships with a link model?\r\n- ...or could the same be achieved by using a one-to-many with `back_populates`?\r\n- The sqlalchemy error is quite cryptic (at least to me). I seem to already have specified the foreign_key on the `UserLink` model columns but apparently I need to specify it differently or somewhere else as well. What else is needed to make this work?\n\n### Operating System\n\nLinux\n\n### Operating System Details\n\n_No response_\n\n### SQLModel Version\n\n0.0.4\n\n### Python Version\n\n3.9.5\n\n### Additional Context\n\n_No response_","author":{"url":"https://github.com/AartGoossens","@type":"Person","name":"AartGoossens"},"datePublished":"2021-09-10T14:10:27Z","url":"https://github.com/fastapi/sqlmodel/issues/89"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:95e8089a-6f55-e7e9-c7bd-2a0302518ed8 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | DFF0:36768A:7AFD09:AE01DA:6AFE1692 |
| html-safe-nonce | ea98aad8ad9d27765cb8ac2c66b58f7b4451e145f7ebd8c2e5f9ca891a3c48ba |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERkYwOjM2NzY4QTo3QUZEMDk6QUUwMURBOjZBRkUxNjkyIiwidmlzaXRvcl9pZCI6IjI0ODgxODk5MDIwMDk1MzgxOTQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | ca49f18b82f9f3a829faef5539f00645492937539301bd2abef12e74c79cdbb1 |
| hovercard-subject-tag | issue:993273375 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/fastapi/sqlmodel/89/issue_layout |
| twitter:image | https://opengraph.githubassets.com/82fcd3b5066244f97535080eea988d03811c96aec1ed65d98fa26383fe779dc2/fastapi/sqlmodel/issues/89 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/82fcd3b5066244f97535080eea988d03811c96aec1ed65d98fa26383fe779dc2/fastapi/sqlmodel/issues/89 |
| og:image:alt | 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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | AartGoossens |
| hostname | github.com |
| expected-hostname | github.com |
| None | d0525ab1464526bf4532a5551aa348cf100dff75ef808a96fc67a08b1d946aa9 |
| turbo-cache-control | no-preview |
| go-import | github.com/fastapi/sqlmodel git https://github.com/fastapi/sqlmodel.git |
| octolytics-dimension-user_id | 156354296 |
| octolytics-dimension-user_login | fastapi |
| octolytics-dimension-repository_id | 399495186 |
| octolytics-dimension-repository_nwo | fastapi/sqlmodel |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 399495186 |
| octolytics-dimension-repository_network_root_nwo | fastapi/sqlmodel |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | fef3993a71fa20f7be8e167132fbf9619bc66e12 |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width