我有点困惑。我试图从SQLalchemy(ORM)开始。我给你带来了一个小的可执行示例代码。那你总共看到三张桌子。简而言之:多对多的关系。 产品和订单是正常的'表。 order_product 是一个分配表。您还会看到我在产品和订单的表格中插入了一些记录。到目前为止,所有记录都保存在每个表中。它就像一个魅力。而现在的问题。如何在分配表中保存ID?设计是什么样的?如何使用分配表?到目前为止,分配表是空的。
更新 - 指定问题
大多数示例显示如何使用关联模式,但仅限于同时发生翻转时。例如,用户首先保存产品,然后保存订单,最后他将两个不同的东西(分配表)联系起来。但是......想象......用户保存产品......一小时后他保存了订单。一天后,他想将产品和订单联系起来。在我的想象中,我必须找出订单的ID,然后必须找出产品的ID ...现在,我可以联系它,对吧?但是如何?
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy
#memory_url = 'sqlite:///:memory:')
#sqlite_url = 'sqlite:///test.db'
mysql_url = '{dbms}+{dbdriver}://{dbuser}:{dbuser_pwd}@{db_server_host}:{dbport}/{db_name}'.format(
dbms='mysql', dbdriver='pymysql', dbuser='root', dbuser_pwd='', db_server_host='localhost', dbport=3306, db_name='test')
engine = sqlalchemy.create_engine(mysql_url, echo=True)
Base = declarative_base()
class Order_Product(Base):
__tablename__ = 'order_product'
order_id = Column(Integer, ForeignKey('orders.id'), primary_key=True)
product_id = Column(Integer, ForeignKey('products.id'), primary_key=True)
quantity = Column(String(30))
order = relationship("Order", backref=backref("order_product", lazy='dynamic', cascade="all, delete-orphan" ))
product = relationship("Product", backref=backref("order_product", lazy='dynamic', cascade="all, delete-orphan" ))
def __init__(self, order, product, quantity):
self.order = order
self.product = product
self.quantity = quantity
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True, unique=True)
name = Column(String(80))
orders = relationship("Order", secondary="order_product")
def __init__(self, name):
self.name = name
class Order(Base):
__tablename__ = 'orders'
id = Column(Integer, primary_key=True, unique=True)
name = Column(String(80))
orders = relationship("Product", secondary="order_product")
def __init__(self, name):
self.name = name
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
prod1 = Product(name="Oreo")
prod2 = Product(name="Hide and Seek")
prod3 = Product(name="Marie")
prod4 = Product(name="Good Day")
session.add_all([prod1, prod2, prod3, prod4])
session.commit()
order1 = Order( name = "First Order")
order2 = Order( name = "Second Order")
order3 = Order( name = "Third Order")
order4 = Order( name = "Fourth Order")
session.add_all([order1, order2, order3, order4])
session.commit()