为什么SQLAlchemy关联对象中的外键被标记为主键?

问题描述 投票:0回答:1

以下是sqlalchemy的文档。

注意对于Association Class中的left_id和right_id,它们首先被标记为ForeignKey,然后是primary_key = True

我认为它们应该是外键是有道理的,因为从逻辑上讲它们是其他两个父表和子表的外键。

那么将它们作为主键的目的是什么呢?

这里发生了什么?请解释。

class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child", back_populates="parents")
    parent = relationship("Parent", back_populates="children")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association", back_populates="parent")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship("Association", back_populates="child")
python sqlalchemy flask-sqlalchemy
1个回答
2
投票

这不是SQLAlchemy独有的。这就是many-to-many relationships的设计方式,它基于关系数据库设计的原理。

在多对多关系中,需要一个附加表,也称为关联表,它将来自第一个表的条目与来自第二个表的相应条目进行映射。

定义关联表时,我们需要一些主键来唯一标识关联表中的记录。拥有主键可创建索引,从而加快连接操作和搜索记录。

那么,为什么将所有外键作为关联表的主要部分?这是为了确保a的记录table Ab的记录Table B没有重复的条目。换句话说,为了确保关系的独特性,从而避免重复关系。

可以在不将外键声明为主键的情况下创建关联表。但这不可取。通过这样做,除非明确创建索引,否则连接操作会变慢。并且,很有可能重复记录Table ATable B之间的关系

© www.soinside.com 2019 - 2024. All rights reserved.