简体   繁体   English

SQLAlchemy查询联接路径从“中间”开始

[英]SQLAlchemy query join path starting from the 'middle'

I have the below models (for a booking service) 我有以下型号(用于预订服务)

from sqlalchemy_utils import ArrowType

class User:
    id = db.Column(db.Integer, primary_key=True)
    name = Column(db.String(80))

class Service:
    desc = Column(db.String(100))
    provider_id = Column(db.Integer, db.ForeignKey('user.id')
    provider = relationship('User', backref='services')

class TimeSlot:
    start = Column(ArrowType)
    owner_id = Column(db.Integer, db.ForeignKey('user.id')
    owner = relationship('User', backref ='timeslots')

I am trying to perform a join, starting from the User , 我正在尝试从用户开始执行联接

users = (
    db.session.query(User)
        .join(Service)
        .join(TimeSlot)
        .options(contains_eager(User.services, User.timeslots)
                 )
        .filter(Service.desc == 'Fun')
        .filter(TimeSlot.start == arrow.get('2015-06-15T19:00:00+00:00'))
        .all()
    )

# would like to list the results in a 'nested' way.
for u in users:
    print(u)
    for ts in u.timeslots:
       print(' ', ts)
    for svc in u.services:
       print(' ', svc)

However, I am getting the below error, 但是,我收到以下错误,

Attribute 'User.timeslots' does not link from element 'Mapper|Service|service' 属性“ User.timeslots”未从元素“ Mapper | Service | service”链接

I understand as much that it is because of the order of the .join() and thaat Service and TimeSlot are not joined. 我完全了解这是因为.join()的顺序,而且thaat服务和TimeSlot没有连接。

How should I go about achieving getting a list of users and their timeslots + services? 我应该如何获得用户列表及其时隙和服务?

Thanks 谢谢

users = (
db.session.query(User)
    .join(Service)
    .join(TimeSlot)
    .options(contains_eager(User.services), contains_eager(User.timeslots))
    .filter(Service.desc == 'Fun')
    .filter(TimeSlot.start == arrow.get('2015-06-15T19:00:00+00:00'))
    .all()
)

try from_joinpoint : 尝试from_joinpoint

q = session.query(Node).\
    join("children", aliased=True).\
    filter(Node.name='child 1').\
    join("children", aliased=True, from_joinpoint=True).\
    filter(Node.name == 'grandchild 1')

or reset_joinpoint: 或reset_joinpoint:

http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.reset_joinpoint http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.reset_joinpoint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM