2012-08-16 129 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