我有 3 个表:Account
、User
和 Organization
。
Account
由id
、name
和organization_id
组成。User
由email
和organization_id
组成。Organization
由id
和name
组成。
每个 Account
都注册到一个 Organization
(通过 organization_id
),每个 User
都注册到一个 组织
。挑战是显示所有电子邮件(来自 User
)到与 name
对应的 Account
,其 organization_id
匹配用户
的organization_id
。
到目前为止,这是我的代码:
class Account(db.Model):
__tablename__ = "account"
id = Column(Integer, primary_key=True)
name = Column(String(50), index=True, unique=True)
organization = Column(Integer,
ForeignKey("organization.id"),nullable=False, index=True)
class User(UserMixin, db.Model, RBACUserMixin):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
organization = Column(Integer, ForeignKey("organization.id"),
nullable=False, index=True)
class Organization(db.Model):
__tablename__ = "organization"
id = Column(Integer, primary_key=True)
name = Column(String(512))
users = relationship("User", backref="organizations")
accounts = relationship("Account", backref="organizations")
最佳答案
根据组织 ID 加入用户和帐户,并根据名称进行过滤:
db.session.query(User.email).\
join(Account, Account.organization == User.organization).\
filter(Account.name == 'some name')
Query.join()
允许在使用 2 参数形式时将任意 SQL 表达式作为 on-clause 传递。
关于python - 如何在 SQLAlchemy 中连接两个表中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50617343/