开发者

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

I have tried something like 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

Any help appreciated


Why is that ugly? It only takes 1 statement (with no SQL at all) to sum up all the file sizes. Though if you want, you may be able to use HQL like so:

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. 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.


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). If you rename it to 'length', 'fileSize', etc. then this will work:

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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜