如何在Eve-SQLAlchemy中查询指定组织下的用户资源?
解决Eve-SQLAlchemy多对多关联的嵌套查询问题
首先咱们先修正模型定义里的一个关键疏漏:你的代码缺少了relationship和ForeignKey的导入,这会直接导致关联关系无法正常建立。请更新模型代码如下:
from sqlalchemy import Column, DateTime, func, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship # 新增这个导入 Base = declarative_base() class BaseModel(Base): id = Column(Integer, primary_key=True, autoincrement=True) __abstract__ = True _created = Column(DateTime, default=func.now()) _updated = Column(DateTime, default=func.now(), onupdate=func.now()) _etag = Column(String(40)) class User(BaseModel): __tablename__ = 'app_user' # 完善关联关系定义,添加反向关联的映射 organizations = relationship("Organization", secondary=UserOrganization.__tablename__, back_populates="users") class Organization(BaseModel): __tablename__ = 'organization' name = Column(String) # 添加反向关联,方便双向查询操作 users = relationship("User", secondary=UserOrganization.__tablename__, back_populates="organizations") class UserOrganization(BaseModel): __tablename__ = 'user_organization' user_id = Column(Integer, ForeignKey('app_user.id', ondelete='CASCADE')) organization_id = Column(Integer, ForeignKey('organization.id', ondelete='CASCADE'))
接下来针对你要查询「属于指定组织的所有用户」的需求,Eve-SQLAlchemy支持通过关联对象的字段进行过滤,你需要使用以下格式的查询:
GET localhost:5000/user?where={"organizations.id": 2}
为什么之前的查询会失败?
{"organizations": {"organization_id" :2 }}:这个写法有误,organizations是关联到Organization模型的集合,而organization_id是中间表user_organization的字段,并非Organization模型本身的字段,Eve无法识别这种嵌套逻辑。{"organizations": 2}:这种写法仅适用于一对一关系或关联字段直接存储id的场景,但多对多关系下organizations是一个集合,无法直接匹配单个id值。
补充说明
如果你的Eve-SQLAlchemy 0.5.0版本对这种嵌套字段过滤支持有限,你也可以尝试直接通过中间表字段构建查询,但需要先将user_organization注册到DOMAIN配置中。不过更简洁可靠的方式还是使用上面提到的关联对象id过滤方式。另外请确保你的Eve应用已正确加载所有模型,且user资源的allow_where选项没有限制相关字段的查询(默认是允许的)。
内容的提问来源于stack exchange,提问作者Justin Beall
相关产品推荐
相关产品推荐

