简体   繁体   中英

Eager Loading Adjacency List Relationship

I have the database schema below

class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('node.id'))
    data = Column(String(50))
    children = relationship("Node")

    def get_data(self):
        x = session.query(Node).options(joinedload(Node.children)).filter(Node.parent_id == None).all()
        return x

The problem is the sqlalchemy function get_data is lazy loading that is it will emmit 100 sql queries if there are 100 children but i need sqlalchmey to fetch all parent nodes and their children with one sql statement. Is this possible?

[Update]

I have the following recursive function that is being used to display a Node and its Children

def get_tree(base_page,dpth=0):
    for child in base_page:
        print " "*dpth, child.data
        get_tree(child.children, dpth= dpth+1)
data = new_node.get_data()
for zz in data:
    get_tree(zz.children)

As you can see the above function will emit alot of queries if i use lazy loading.

I do not think you can make it using purely sqlalchemy , because MySql does not support recursive queries (or recursive CTE ). See this answer Generating Depth based tree from Hierarchical Data in MySQL (no CTEs) .
You can, of course, preload one or two levels by using joinedload and contains_eager .

Alternatively, you could however, write a stored procedure and call it from SA using from_statement .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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