关联查询 join的使用

时间:2024-05-10 00:03:13
 #!/usr/bin/env python
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
print(sqlalchemy.__version__) engine = create_engine('mysql+pymysql://root:taochen123@127.0.0.1:3306/a1',echo = True) Base = declarative_base(engine) class Father(Base):
__tablename__ = "father" id = Column(Integer,autoincrement=True,primary_key=True)
name = Column(String(20))
son = relationship('Father')
def __repr__(self):
return self.name class Son(Base):
__tablename__ = 'son'
id = Column(Integer,autoincrement=True,primary_key=True)
name = Column(String(20))
email = Column(String(20))
father_id = Column(Integer,ForeignKey('father.id'))
Base.metadata.create_all(engine) Session = sessionmaker(bind=engine)
session = Session()
# f1 = Father(name = "fafafa")
# session.add(f1)
# s1 = Son(name = 'sq',email = '@qq.com',father_id = 1)
# s2 = Son(name = 'sw', email= 'q@qq.com',father_id= 1)
# session.add_all([s1,s2]) ret = session.query(Father.name,Son.name).join(Son).first()
print("ret=",ret)
session.commit()