0

我有以下模型:

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 类。

我认为为了做到这一点,我需要对第一次的结果进行第二次搜索,但我不知道该怎么做。

有什么建议么?

谢谢你,

乔波

4

1 回答 1

0

You shouldn't define an id field unless it's different from the one that GORM adds for you - it adds a Long id by default, so yours isn't needed. Also, your belongsTo names are very nonstandard - the _id suffix should be removed. And what's the deal with all of those semicolons ;)

Given this domain class:

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

Then you can get the most recent posts for each author for a specified category with this HQL query (I have no idea how to do it with a Criteria query):

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])
于 2013-03-10T19:41:47.287 回答