我需要帮助在域类之间创建关联。我有三个域:用户,新闻,评论。用户可以对许多新闻发表很多评论。新闻可以有很多用户的评论。
我在GORM中实现这种关联存在很大问题。
我希望用户能够为新闻项添加评论。评论应该引用制作它的用户。新闻项目应该包含所有评论的列表。
域类:
sqlite3
IntegrationTests包括:
class User {
String nickName
String password
Date dateCreated
static hasMany = [users : User, comments : Comment]
static hasOne = [profile : Profile]
//static belongsTo = [comments : Comment]
static constraints = {
profile nullable: true
}
}
class News {
String webTitle
String webPublicationDate;
String trailText;
String webUrl;
String thumbnail;
String webId;
static hasMany = [tags : Tag, comments : Comment]
static constraints = {
}
}
class Comment {
//static belongsTo = [news : News, user : User]
String content
int likes
int disLikes
Date lastUpdated
static hasOne = [user: User, news: News]
static constraints = {
}
}
任何帮助将不胜感激
答案 0 :(得分:1)
我宁愿稍微更改您的域类:
class User {
String nickName
String password
Date dateCreated
static hasMany = [users : User, comments : Comment]
static hasOne = [profile : Profile]
static constraints = {
profile nullable: true
}
}
class Communicate { //because News could possibly create troubles during generating controller or test classes (it's the same as singular and plural)
String webId;
String webTitle
String webPublicationDate;
String trailText;
String webUrl;
String thumbnail;
static hasMany = [tags : Tag, comments : Comment]
static constraints = {
}
}
class Comment {
static belongsTo = [user: User, communicate: Communicate] //read more about it: http://docs.grails.org/latest/ref/Domain%20Classes/belongsTo.html
String content
int likes
int disLikes
Date lastUpdated
static constraints = {
}
}
在这些更改之后,您应该重新创建这些表(如果它仍处于开发阶段,则创建完全删除db。)
此外,通过向评论添加belongsTo
语句,您应该修复您的测试(user
并且“创建时”将需要“通信”属性:
def comm = new Comment(content: "Hillary cant be president", user:user, communicate:news)