2014-09-01 70 views
0

我有一个Grails领域,看起来像下面Grails领域瞬态和计算

User { 
    sortedSet notifications 
    static hasMany=[notifications:Notification] 
} 

Notification { 
    Date dateCreated 
    int status=0 
    static belongsTo=[user:User] 

    @Override 
    public int compareTo(obj) { 
    dateCreated.compareTo(obj.dateCreated) 
    } 
} 

如果我返回“用户”对象的GSP,有没有办法让所有的通知,其中状态的计数= 1。

例如:user.notifications.size()(但是其中状态= 1)

而不必返回另一个单独的通知对象。

回答

1

你提到这个词在标题为“瞬态”,但在其他地方。你想声明一个短暂的财产做这样的事情?......

class User { 
    SortedSet notifications 
    static hasMany=[notifications:Notification] 
    static transients = ['numberOfStatusOnes'] 

    int getNumberOfStatusOnes() { 
     notifications?.count { it.status == 1 } ?: 0 
    } 
} 
+0

嗨,谢谢,这是最好的解决方案! – 2014-09-02 10:11:18

0

可以使用namedQueries或相似:

class User { 

    static hasMany=[notifications:Notification] 

    static namedQueries = { 
    notificationsByStatus{ int status = 1 -> 
     notifications{ 
     eq 'status', status 
     } 
    } 
    } 
} 

你可以打电话查询,以便

User.notificationsByStatus.count() 
+0

在那种很接近......的“通知”想出了一个下划线...例如,它不能解决呢?当我尝试启动程序并寻找$ {user.notificationsByStatus}它无法解决此问题。“没有此类属性:notificationsByStatus为类:tutor.com.User” – 2014-09-01 12:37:59

+0

$ {user.notificationsByStatus}不应该工作在所有。你必须调用'$ {user.notificationsByStatus.count()}'或'$ {user.notificationsByStatus.list()}' – injecteer 2014-09-01 12:39:54

+0

你正在使用哪个grails版本? – injecteer 2014-09-01 12:40:18

0

如果我返回“用户”对象的GSP,是有什么办法获得状态= 1的所有通知的 计数

由于您正在将User返回给GSP,因此我认为有一些原因需要该对象并构建不同的查询,该查询只返回状态1通知不是您想要的。相反,您可以询问User并获取所需的信息。

在你的控制器,该控制器retriving用户对象,你可以做这样的事情:

def someAction() { 
    User u = // you got your user from somewhere: 
    int numberOfStatusOnes = u.notifications.count { it.status == 1 } 

    [user: u, numberOfStatusOnes: numberOfStatusOnes] 
} 

然后在你的GSP当你指的user将成为User类的实例,当你参考numberOfStatusOnes,这将是一个数字,表示有多少Notification s表示User具有有status 1.