gid*_*mot 1 templates frameworks list playframework
在Play框架中,如何从数据库中仅列出特定数量的对象而不是全部.假设我有这个Post类与注释的@OneToMany关系就像这样
public class Post extends Model {
@ManyToOne
public User user;
public String name;
public String description;
public String image;
public Date created_date;
@OneToMany(mappedBy="post", cascade=CascadeType.ALL)
public List<Comment> comments;
....
}
Run Code Online (Sandbox Code Playgroud)
如何仅为模板中的每个帖子列出前5条评论?我已经完成了这个,但它显示了所有评论
#{list items:post.comments, as:'comment'}
<p>${comment.comment}</p>
#{/list}
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以使用标准Java来获取子列表
#{list items:post.comments.subList(0,5), as:'comment'}
<p>${comment.comment}</p>
#{/list}
Run Code Online (Sandbox Code Playgroud)
如果少于5个注释,上面将返回一个超出范围的数组索引,因此您可以在模板中添加更多逻辑(如下所示),或者您可以在Post模型中创建获取前5个注释的getter方法,而只是调用它(这可能是更清洁和首选的选项.
模板中的额外逻辑看起来像
#{list items:post.comments.subList(0, Math.min(5, post.comments.size())), as:'comment'}
<p>${comment.comment}</p>
#{/list}
Run Code Online (Sandbox Code Playgroud)
如果您认为这在您的视图中有太多逻辑,并且想要将其封装在模型中,则可以执行以下操作.您视图中的额外逻辑可能看起来像
public List<Comment> getTop5() {
return comments.subList(0, Math.min(5, comments.size());
}
Run Code Online (Sandbox Code Playgroud)
然后你的控制器就是
#{list items:post.top5, as:'comment'}
<p>${comment.comment}</p>
#{/list}
Run Code Online (Sandbox Code Playgroud)