2013-01-11 45 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()