简体   繁体   English

Grails一对多

[英]grails sum one-to-many

I need a help with what I believe is very trivial stuff. 我认为非常微不足道的东西需要帮助。

class User {
    String name 
    static hasMany = [files : File]
}

class File {
    long size
}

Now when I need the total size of all files a given user has I use the following which is working : 现在,当我需要给定用户拥有的所有文件的总大小时,可以使用以下有效的方法:

def user = User.get(id)
user.files.each(total+=it.size)

but how ugly is it, when I am sure it can be done with simple select sum query with either plain SQL or GORM/CRITERIA 但是有多丑,当我确定可以用简单的选择和查询(使用普通SQL或GORM / CRITERIA)完成时

I have tried something like File.sumBySize..() 我已经尝试过类似File.sumBySize ..()

Or 要么

def c = File.createCriteria()
def f = c.list{
    eq("user",  user)   // What here ?
    projections
        {
        sum("size")
        }
    }   

I dont know how to specify the parent(user) relationship which is not defined in File class but in Grails join tables 我不知道如何指定在File类中未定义但在Grails联接表中定义的parent(用户)关系

Any help appreciated 任何帮助表示赞赏

Why is that ugly? 为什么这么丑? It only takes 1 statement (with no SQL at all) to sum up all the file sizes. 只需1条语句(根本没有SQL)即可总结所有文件大小。 Though if you want, you may be able to use HQL like so: 虽然,如果您愿意,您可以像下面这样使用HQL:

def user = User.get(id)
def sum = File.executeQuery("select sum(f.size) from File f where f.user = ?", user);

But I think you'd need to add a belongsTo to File to do that. 但是我认为您需要在文件中添加一个belongsTo。 There's probably a simpler HQL/GORM method that's just not coming to my mind at the moment, but honestly, I don't think there's anything easier than what you already did. 目前可能还没有想到一种更简单的HQL / GORM方法,但老实说,我认为没有什么比您已经做的容易。

You can do it with an HQL query, but it has a small problem with the name of the 'size' field (appears to be a reserved word). 您可以使用HQL查询来执行此操作,但是“大小”字段的名称存在一个小问题(似乎是保留字)。 If you rename it to 'length', 'fileSize', etc. then this will work: 如果将其重命名为“ length”,“ fileSize”等,那么它将起作用:

User.executeQuery(
   'select sum(file.length) from User u join u.files file where u.id=:userId',
   [userId: id])[0]

A more elegant way to sum the file sizes in Groovy code is: 用Groovy代码总结文件大小的一种更优雅的方法是:

def total = user.files.sum {it.size}

But if you can calculate the file size totals in the query that returns the users, that's the way I'd do it. 但是,如果您可以在返回用户的查询中计算文件大小的总和,那就是我要做的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM