2013-01-11 37 views
0

在我的查詢中使用很多與左外連接有關的表, 我想知道是否有任何方法可以輕鬆地將查詢結果作爲基本數組,可以期望在phpmyadmin例如(我不是說佈局)。讓SqlAlchemy作爲一個數組加入查詢結果

給定3個表格,所有表格都被映射,我現在只獲得第一個表格作爲對象的結果,如果有任何table2結果,我必須對其進行測試,等等,對於表格3 :

list_res_table1 = DBSession.query(table1).outerjoin(table2).outerjoin(table3).all() 
for res_table1 in list_res_table1: 
    if res_table1.relationship_to_table2: 
     list_res_table2 = res_table1.relationship_to_table2 
     for res_table2 in list_res_table2: 
      if res_table2.relationship_to_table3: 
       etc. 

這將是巨大的,獲得對象,如直接訪問列表:

((table1, table2, None) #=> no result for table3 
(table1, None, None)  #=> no result for table2 
(table1, table2, table3)) #=> results for all tables 

回答

2

你可以(當然應該)查詢此直接,如:

list_res_table1 = DBSession.query(table1, table2, table3).outerjoin(table2).outerjoin(table3).all() 

加入將首先查看最左邊的表格。如果你需要更多的特異性,你可以添加select_from()以及顯式ON子句:

list_res_table1 = DBSession.query(table1, table2, table3).\ 
         select_from(table1).\ 
         outerjoin(table2, table2.c.id==table1.c.t2id).\ 
         outerjoin(table3, table2.c.t3id==table3.c.id).all()