如何在SQLAlchemy中执行此递归公用表表达式?

nub*_*ela 4 python sql sqlalchemy

在此表架构中:

class Location(db.Model):
    id = db.Column(db.String(255), primary_key=True)
    parent_id = db.Column(db.String(255), db.ForeignKey('location.id'), nullable=True) 
    type = db.Column(db.String(255))
    name = db.Column(db.String(255))
    options = db.Column(db.Text, nullable=True)
Run Code Online (Sandbox Code Playgroud)

我有一个父母,假设这个表:

> select * from location;
+--------------------------------------+--------------------------------------+---------+-----------+---------+
| id                                   | parent_id                            | type    | name      | options |
+--------------------------------------+--------------------------------------+---------+-----------+---------+
| 8821da60-e7d2-11e1-951e-ae16bc2b7368 | 88227a60-e7d2-11e1-951e-ae16bc2b7368 | city    | sengkang  | NULL    |
| 88227a60-e7d2-11e1-951e-ae16bc2b7368 | NULL                                 | country | singapore | NULL    |
+--------------------------------------+--------------------------------------+---------+-----------+---------+
Run Code Online (Sandbox Code Playgroud)

父母是名为singapore国家/地区对象.可以有多个嵌套的对象,是孩子们盛港随便怎么样都盛港是孩子新加坡.

因此,单个层链可能看起来像 - > b - > sengkang - >新加坡

据此 - >意思是孩子的

如何获得父母为新加坡的所有位置对象,包括父对象(新加坡)?(请在SQLAlchemy中).谢谢!

Ton*_*bbs 6

SA文档:Query.cte

我不得不说,新的CTE的东西(因为0.76)是相当不错的,比老办法,我必须返工更好这个.

无论如何,认为你正在寻找这样的东西......

included_parts = session.query(Location).\
  filter(Location.name=='singapore').\
  cte(name='included_parts', recursive=True)

incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Location, name='p')
included_parts = included_parts.union_all(
  session.query(parts_alias).filter(parts_alias.parent_id==incl_alias.c.id)
)

q = session.query(included_parts).all()
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说没有任何"别名" - 我错过了什么吗? (2认同)