結合多個SQL資料庫內的表單
如何將同個資料庫內的各個資料表相關連結串啟成為自己想要的資訊,這時候會用到 relationship
。
大概解釋一下用法 : A欄位 = relationship ("B表單",back_populates="B欄位")
。
py
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
當有2個資料表,有共同欄位串聯時。
py
class TABLE_A(Base):
__tablename__="table a"
...
items = relationship("TABLE_B", back_populates="owner")
class TABLE_B(Base):
__tablename__="table b"
...
owner = relationship("TABLE_A", back_populates="items")
多個資料表時呢 ? 下方做個範例 :
py
class TABLE_A(Base):
__tablename__ = "table_a"
...
item_same = relationship("TABLE_B", back_populates="item_same")
item_A_1 = relationship("TABLE_B", back_populates="item_B_1")
class TABLE_B(Base):
__tablename__ = "table_b"
...
item_same = relationship("TABLE_C", back_populates="item_same")
item_B_1 = relationship("TABLE_C", back_populates="item_C_1")
class TABLE_C(Base):
__tablename__ = "table_c"
...
item_same = relationship("TABLE_A", back_populates="item_same")
item_C_1 = relationship("TABLE_A", back_populates="item_A_1")
這裡敘述三張表單都有相同欄位 item_same
,從 TABLE_A -> TABLE_B -> TABLE_C 串聯。