首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Long chain在链中存在多个一对多映射的查询。

Long chain在链中存在多个一对多映射的查询。
EN

Stack Overflow用户
提问于 2014-01-20 09:14:53
回答 1查看 115关注 0票数 1

编辑:下面的文章似乎是正确的方法:session.query(User).join("userGadgets", "gadget", "components","gadgetComponentMetals")

原始:配置了以下表:

代码语言:javascript
复制
class User(Base):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True)
    name = Column(String)


class Gadget(Base):
    __tablename__ = "gadget"

    id = Column(Integer, primary_key=True)
    brand = Column(String)


class UserGadget(Base):
    __tablename__ = "user_gadget"

    user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
    gadget_id = Column(Integer, ForeignKey('gadget.id'), primary_key=True)

    user = relationship("User", backref=backref('userGadgets', order_by=user_id))
    gadget = relationship("Gadget", backref=backref('userGadgets', order_by=gadget_id))


class GadgetComponent(Base):
    __tablename__ = "gadget_component"

    id = Column(String, primary_key=True)
    gadget_id = Column(Integer,ForeignKey('gadget.id'))
    component_maker = Column(String)

    host = relationship("Gadget", backref=backref('components', order_by=id))


class ComponentUsingMetal(Base):
    __tablename__ = "component_metal"

    id = Column(Integer, primary_key=True)    
    component_id = Column(Integer, ForeignKey('GadgetComponent.id'))  
    metal = Column(String)

    component = relationship("GadgetComponent", backref=backref('gadgetComponentMetals', order_by=id))

我想为拥有至少一个含有某种金属的部件的用户找到所有的用户名。对此的SQL查询将遵循以下内容:

代码语言:javascript
复制
SELECT distinct u.name FROM user u join user_gadget ug on (u.id = ug.user_id) join gadget_component gc on (ug.gadget_id = gc.id) join component_metal cm on (gc.id = cm.component_id) order by u.name

我试过不同的版本,如:session.query(User).filter(User.userGadgets.any(UserGadget.gadget.components.any(GadgetComponent.gadgetComponentMetals.exists())))

我得到以下错误:AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with UserGadget.gadget has an attribute 'gadgetComponents'

对于我做错了什么,或者在SQLAlchemy中有更好的方法来执行这种查询,有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-25 02:48:27

join()是这里更好的方法,因为任何()都会产生许多昂贵的嵌套子查询。但是,您使用"any“的错误是使用了类似于:UserGadget.gadget.components的语法。在类似的系列中,SQLAlchemy不会继续属性的命名空间,例如没有UserGadget.gadget.components;只有UserGadget.gadgetGadget.components。就像SQL不允许您说"SELECT * from user_gadget.gadget_id.gadget.component_id“之类的一样,SQLAlchemy需要您告诉它如何将您正在查询的多个表连接在一起。在这里使用any()将类似于any(and_(UserGadget.gadget_id == GadgetComponent.gadget_id)),但无论如何使用联接更好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21230065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档