1.首先创建两实体
2.创建中间表
3.在其中一个模型中建立relathionship属性,来绑定三个表之间的关系,在使用relationship的时候需要传入一个secondary=中间表
from flask import Flask, jsonify, json
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, func, and_, or_, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
# 连接数据库字符串
DB_URI = "mysql://root:123456@127.0.0.1/pyDemo?charset=utf8mb4"
engine = create_engine(DB_URI)
# 判断是否连接成功
engine.connect()
# 创建ORM
Base = declarative_base(engine)
# 创建回话
session = sessionmaker(engine)()
#中间表
article_tag = Table(
"article_tag",
Base.metadata,
Column("article_id", Integer, ForeignKey("article.id"), primary_key=True),
Column("tag_id", Integer, ForeignKey("tag.id"), primary_key=True)
)
# 文章
class Article(Base):
# 表名字
__tablename__ = 'article'
# 列
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), default='1111')
def __repr__(self):
return "<Article(title:%s)>" % self.title
#标签表
class Tag(Base):
# 表名字
__tablename__ = 'tag'
# 列
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50))
articles = relationship("Article", backref="tags", secondary=article_tag)
# 生成实体
Base.metadata.drop_all()
Base.metadata.create_all()
# 多对多关系数据操作
article1 = Article(title="title00001")
article2 = Article(title="title00002")
tag1 = Tag(name="tag001")
tag2 = Tag(name="tag002")
article1.tags.append(tag1)
article1.tags.append(tag2)
article2.tags.append(tag1)
article2.tags.append(tag2)
session.add(article1)
session.add(article2)
session.commit()
#查询多对多关系
article = session.query(Article).first()
print(article.tags)
tag = session.query(Tag).first()
print(tag.articles)