2014-10-20 55 views
0

对不起,如果标题不清楚,想不到一个好的方式来制定它。 目前我检查,如果它没有父视图则显示它 我想这个改变控制器(显然)数据库有两种不同的表格要求

我的表:

db.define_table('comments', 
      Field('parent_id', 'reference comments', readable=False, writable=False), 
      Field('body', 'text', label='Message', requires=IS_NOT_EMPTY()), 
      auth.signature) 

db.define_table('comments_users', 
      Field('user_id', 'reference auth_user', requires=IS_NOT_EMPTY()), 
      Field('comments_id', 'reference comments', requires=IS_NOT_EMPTY()), 
      Field('permission', 'integer', requires=IS_NOT_EMPTY())) 

的选择我想那并不是”将不起作用:

rows = db(
      (db.comments_users.user_id==auth.user.id) & 
      (db.comments_users.comments_id.parent_id==0) # something like this is possible in view with a single row 
     ).select(limitby=(0, 10)) 

我现在做中,我想改变控制器

{{for row in rows:}} 
    {{if row.comments_id.parent_id==0:}} 
     <td>{{=row.comments_id}}</td> 
    {{pass}} 
{{pass}} 
视图

回答

1

首先,请注意row.comments_id.parent_idrecursive select - 对于每一行,它都执行单独的选择,获取由row.comments_id标识的db.comments记录。循环遍历所有记录时效率不高,因此不推荐。

递归选择概念不适用于查询,因此您不能像查询中那样执行db.comments_users.comments_id.parent_id == 0。然而,你可以做同样的事情,以创建一个子查询:

no_parents = db.comments_users.comments_id.belongs(db.comments.parent_id == 0) 
db((db.comments_users.user_id == auth.user_id) & no_parents).select(limitby(0, 10)) 

当应用belongs方法的引用类型字段,并通过在查询时,会自动生成一个子查询。有关更多详细信息,请参阅belongs documentation。通过行循环时

db((db.comments_users.user_id == auth.user_id) & 
    (db.comments.parent_id == 0) & 
    (db.comments.id == db.comments_users.comments_id)).select(limitby(0, 10)) 

在这种情况下,虽然:

注意,而不是子查询,它可能是更有效地做一个连接(你可以检查db._timings或使用response.toolbar()调查) ,则需要引用表名和字段名(例如,row.comments.id,row.comments_users.permission等),因为每个对象都将包含来自两个表的字段。

+0

非常感谢你 我在尝试加入之前遇到的问题是我忘记了(db.comments.id == db.comments_users.comments_id)),这只是我身边的愚蠢。 – PrivateerGerrit 2014-10-20 17:33:33

相关问题