将多对多关系中的相关属性映射到它们自己的“虚拟”列

时间:2021-04-26 07:47:09

标签: sqlalchemy

我有两个多对多的相关表,想了解如何将相关表的特定值映射为主题表的属性。

这是我使用 column_property 和关联表的内容:

class Assoc_Table(Base):
  __tablename__ = 'assoc_table'
  __table_args__ =  {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

  a_id = Column(Unicode(255), ForeignKey('a.id'), primary_key=True)
  b_id = Column(Integer, ForeignKey('b.id'), primary_key=True)


class A(Base):
  __tablename__ = 'a'
  __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

  id   = Column(Unicode(255), primary_key=True)
  bees = relationship("B", secondary="assoc_table", back_populates="as")


class B(Base):
  __tablename__ = 'b'
  __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

  id       = Column(Integer, primary_key=True)
  as       = relationship("A", secondary="assoc_table", back_populates="bees")
  name     = Column(Unicode(255))
  category = Column(Integer)

此数据的使用者之一要求表 A 应提供多个列(column_property/hybrid_property/plain_descriptor/something else?),其中包含关联 A.bees 集合中几个不同项目的名称属性。像这样:


class A(Base):
  __tablename__ = 'a'
  __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}

  id   = Column(Unicode(255), primary_key=True)
  bees = relationship("B", secondary="assoc_table", back_populates="as")
  x    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==1)).limit(1), deferred=True)
  y    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==1)).limit(2), deferred=True)
  z    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==2)).limit(1), deferred=True)


(如果语法有点古怪,请见谅,但这与 ATM 实现的很接近)。

映射属性 Ax 和 Ay 旨在保存 B.category 上匹配的第一个和第二个相关 B 表记录的名称属性(如果没有第一个/第二个相关记录,则为 None),类似地,Az 应该保存第一个相关 B 表记录的名称属性。 A.x & A.z 大致做了他们应该做的,但我不知道如何将 A.y 映射到第二个相关 B 记录的 name 属性。

这甚至是尝试建模的有用方法吗?我已经定义了 A.bees 关系 - 我可以使用它来填充 A.x、A.y 和 A.z 列吗?

我觉得我表达的不是很清楚,如果这不合理,请随时要求澄清...谢谢!

1 个答案:

答案 0 :(得分:0)

事实证明它真的没有那么难(甚至真的是一个 sqlalchemy 问题!)。问题中的方法是完全有效的,只需要 SQL 将第二条记录选择到 'y' column_property 中。对于 MySQL(此问题的目标数据库),以下语法达到了目标:

  x    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==1)).limit(1), deferred=True)
  y    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==1)).offset(1).limit(1), deferred=True)
  z    = column_property(select([B.name]).where(and_(Assoc_Table.a_id==id, Assoc_Table.b_id==B.id, B.category==2)).limit(1), deferred=True)

相关问题