我希望能够通过SQLAlchemy中的多个多对多关系进行查询。通过SQLAlchemy选择多个多对多关系
我有用户,这些用户与组关联到角色。所有的关联都是多对多的。我想通过组获得与用户关联的角色列表。
这里是我的条纹向下的模型:
class User(Model):
id = Column(Integer)
groups = relationship('Group', secondary=user_group)
class Group(Model):
id = Column(Integer)
roles = relationship('Role', secondary=role_group)
class Role(Model):
id = Column(Integer)
我有什么SQL将被用来粗略的想法:
select distinct role.* from role, role_group
where role.id = role_group.role_id
and role_group.group_id in
(select "group".id from "group", user_group
WHERE user_group.user_id = 1
and "group".id = user_group."group.id")
,但我有一个很难搞清楚如何把这种到SQLAlchemy中...并且我不确定即使这里的SQL是执行此操作的最佳方法。
完美。这正是我所期待的。如果您在原始问题中注意到我确实需要不同的角色(请参阅SQL)。此外,这似乎比我上面写的更适当的SQL。谢谢。 – bpedman