我正在尝试对系统具有用户、公司、组和角色模型的情况进行建模。其中关系如下。
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(Unicode(50), unique=True, nullable=False)
first_name = Column(Unicode(50), nullable=False)
last_name = Column(Unicode(50), nullable=False)
company_id = Column(Integer, ForeignKey('companies.id'))
class Company(Base):
__tablename__ = 'companies'
id = Column(Integer, primary_key=True)
name = Column(Unicode(200), unique=True, nullable=False)
users = relationship("User", backref="company")
groups = relationship("Group", backref="company")
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(Unicode(60), nullable=False)
company_id = Column(Integer, ForeignKey('companies.id'), nullable=False)
roles = relationship("Role", backref="group")
class Role(Base):
__tablename__ = 'roles'
id = Column(Integer, primary_key=True)
name = Column(Unicode(60), nullable=False)
group_id = Column(Integer, ForeignKey('groups.id'), nullable=False)
我的问题是,我不确定如何强制执行约束,即用户不能成为 Group 或 Role 的成员,除非是拥有 Group 的公司的成员。