sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

n:m relation to self

Open kingrodriguez opened this issue 2 years ago • 0 comments

First Check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the SQLModel documentation, with the integrated search.
  • [X] I already searched in Google "How to X in SQLModel" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to SQLModel but to Pydantic.
  • [X] I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • [X] I commit to help with one of those options 👆

Example Code

from typing import Optional

from sqlmodel import Field, Relationship, SQLModel

class FriendsLink(SQLModel, table=True):
    user1_id: Optional[int] = Field(
        default=None, foreign_key="user.id", primary_key=True
    )
    user1_id: Optional[int] = Field(
        default=None, foreign_key="user.id", primary_key=True
    )


class User(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str = Field(index=True)

    friends: List["User"] = Relationship(back_populates="friends", link_model=FriendsLink)

Description

I try to create an n:m relationship with the own model (e.g. user friendship from the example above). Is that even possible? or do i store just plain friend_ids: list[int] in the model?

it feels like i need to pass some SQLAlchemy args there, but i tried for too many hours scouring the docs, which are not that easy to understand (SQLAlchemy) =(

Operating System

Linux

Operating System Details

kernel: 5.15.60-1-MANJARO

SQLModel Version

0.0.8

Python Version

3.9.2

Additional Context

No response

kingrodriguez avatar Sep 21 '22 20:09 kingrodriguez