按外键列对 GORM 查询结果进行排序

Sort GORM query result by a column of a foreign key

我有一个在 Grails 中完全映射的外键关系,比方说:

class Hero {
    Long id
    String name
    Long experience

    Pet pet
    .....
}

class Pet {
    Long id
    String name
    Long ownerId
    .....
}

假设我想查询所有将 Pet 命名为 "Hiccup"Hero。所以我将对 Hero class:

执行查询
def matching = Hero.findAll {
    ilike('pet.name', '%Hiccup%')
}

而且成功了!问题是如何按 PetName 列对返回的 List 进行排序?我试过:

def matching = Hero.findAll {
    ilike('pet.name', '%Hiccup%')
    orderBy('pet.name', 'asc')
}

但它 returns 一个错误:

org.hibernate.QueryException:
could not resolve property: pet.name of: Hero

谢谢。

试试这个:

def matching = Hero.withCriteria {
    pet {
       ilike('name', '%Hiccup%')
       orderBy('name', 'asc')
    }
}

或反过来:

def matching = Pet.withCriteria {
    projections {
        property('hero')
    }
    ilike('name', '%Hiccup%')
    orderBy('name', 'asc')
}

但这仅在您使用 grails 命令声明 pet <--> hero 关系时有效。不知道这是一对一还是一对多

应该是这样的(一对一):

class Hero {
    Long id
    String name
    Long experience

    static hasOne = [pet:Pet]
    .....
}

class Pet {
    Long id
    String name
    Long ownerId
    .....

    static belongsTo = [hero:Hero]
}