2012-08-16 40 views
2

在这个表模式:如何在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) 

我有父母,假设此表:

> 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 | 
+--------------------------------------+--------------------------------------+---------+-----------+---------+ 

父被任命为新加坡国家对象。可以有更多的嵌套对象,那就是子女sengkang就像sengkang是小孩新加坡

所以单层次结构链可能看起来像一个 - “乙 - >盛港 - >新加坡

借此 - >表示

孩子怎样才能有父所有位置的对象作为新加坡,包括父母(新加坡)? (请在SQLAlchemy中)。谢谢!

回答

3

SA文档:Query.cte

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

无论如何,认为你在寻找这样的事情......

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() 
+0

你可以重写你的榜样回答我的问题的情况下?我确实读过这个例子,但没有理解没有上下文的情况。我希望通过我的例子来学习CTE,谢谢! – nubela 2012-08-17 05:24:56

+1

它是/为您的上下文编写的,请注意它是如何查询Location和Location.name =='singapore'的 - 变量名称与示例相同,因为它们只是描述查询部分的通用名称。查询结果是: [(u'88227a60-e7d2-11e1-951e-ae16bc2b7368',None,u'country',u'singapore',None),(u'8821da60-e7d2-11e1-951e-ae16bc2b7368' ,u'88227a60-e7d2-11e1-951e-ae16bc2b7368',u'city',u'sengkang',None)] – 2012-08-17 16:44:55

+0

我明白了,你是绝对正确的,谢谢! – nubela 2012-08-19 08:13:53