Grails找到了关系

时间:2014-03-24 19:23:18

标签: grails groovy

我打破了这个逻辑,我有两个域,用户和RSS。当用户添加RSS时,我必须通过在同一用户中给出另一个URL来比较我的数据库中是否没有重复的URL。

class RSS {
    Long id
    String link
    static belongsTo = [user:User]
}

class User {
    Long id
    Long uid //facebook
    String name
    static hasMany = [rss:RSS]
}

def addRSS(){
//logic url is valid or not
...
 def user = User.findByUid(data.id) //get User uid and then by this uid, i can get the all RSS url
 //and compare like if(db_url == given_url) ...
}

我尝试了很多方法而且没有成功。

2 个答案:

答案 0 :(得分:1)

您还可以使用findOrSaveWherefindOrCreateWhere方法之一

def url = 'some url from user' //data.url I would assume
def user = User.findByUid(data.id)
RSS.findOrSaveWhere(url: url, user: user)

如果它在数据库中,它将为您获取它,如果不是它将为您创建它。该文档解释了*Save**Create*

之间的区别

答案 1 :(得分:0)

我认为简单加入:

def existing = RSS.withCriteria{
  eq 'link', url
  eq 'user.id', userId
}

def existing = RSS.withCriteria{
  eq 'link', url
  user{ eq 'uid', uidd }
}

if( existing ) return
else doSave()