Grails:对criteria.list的结果执行第二次搜索

时间:2013-03-10 19:00:04

标签: grails hibernate-criteria

我有以下型号:

class Post {
  int id;
  String comment;
  static belongsTo = [
    category_id:Category,
    author_id:Author
  ];
}

我希望创建以下查询:找到每个作者的最新帖子(按id),然后只有当他们属于某个类别X时才返回帖子。

到目前为止我已经走了多远:

def cat = Category.findByID(x); // Not yet used

def c = Post.createCriteria();
def results = c.list {
  projections {
    groupProperty("author_id", "myid")
    max("id", "version")
  }
}

def posts = results?.collect{Post.read(it[0])}

诱惑是在like("categorie_id", cat)之前添加projections

但是,这导致每个作者的最后一篇文章与X类相关。

我需要:每个作者的最新帖子,如果它属于X类。

换句话说,我想知道每个作者的最新帖子是否属于x类。

我认为为了做到这一点,我需要对第一个结果进行第二次搜索,但我不知道如何做到这一点。

有什么建议吗?

谢谢,

Chopo

1 个答案:

答案 0 :(得分:0)

您不应该定义id字段,除非它与GORM为您添加的字段不同 - 默认情况下它会添加一个Long ID,因此不需要您的字段。此外,您的belongsTo名称非常不标准 - 应删除_id后缀。与所有这些分号有什么关系;)

鉴于此域类:

class Post {
   String comment
   static belongsTo = [
      category: Category,
      author: Author
   ]
}

然后,您可以使用此HQL查询获取指定类别的每位作者的最新帖子(我不知道如何使用Criteria查询执行此操作):

def category = ...

def posts = Post.executeQuery(
   'select p from Post p where id in (' +
      'select max(p.id) from Post p ' +
      'where p.category=:category group by p.author.id)',
   [category: category])