簡體   English   中英

Grails GORM嵌套的多對多關系查詢

[英]Grails GORM nested has-many relationship query

我嘗試通過以下方式獲取包含一個特定用戶的所有受眾群體的帖子:

StreamPost.findAllByAudience(Friendzone.findAllByFriends(User.findAllById(2)))

要么

def posts = StreamPost.where {
    audience.friends.id ==~ userId
}.list()

的第一個結果

ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - No value specified for parameter 1

第二個也不起作用,返回:

[]

我有以下域模型:

class StreamPost {
    static belongsTo = User
    Friendzone audience

    Date postTimestamp
    String postComment
    String postType

    static constraints = {
        postType inList: ['event','activitylevel','checkin','rating']
    }
}

class Friendzone {
    static belongsTo = User
    static hasMany = [friends:User,
                      streamposts:StreamPost]
    User owner

    String zoneName
    static constraints = {
        owner nullable: false
        friends nullable: false
    }
}

class User {
    static hasMany = [friends:User,
                      friendzones:Friendzone,
                      streamposts:StreamPost]
    static mappedBy  = [ friends: 'friends' ]

    String username
    String password
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static constraints = {
        username nullable: false
        password nullable: true
    }
}

因此,user1可能會為包含其user2和user3的friendzone1做一個可見的帖子。 現在我想獲取所有對user2可見的帖子...

哪種方法是最好的方法? 動態查找器,查詢,條件或hql在哪里? 如何避免前面提到的錯誤?

數據庫方案:

table: user
id  |  username
1   |  user1
2   |  user2

table: user_friendzone
user_id  |  friendzone_id
2        |  1

table: friendzone
id  |  owner_id  |  zone_name
1   |  1         |  user2only

table: stream_post
id  |  audience_id  |  post_comment
1   |  1            |  comment

編輯19.08.2015

我認為friendzone類會引起問題。 通過Emmanuel的評論,我發現嘗試查詢Friendzone時拋出了錯誤(與上述相同)。 例如:

def audience = Friendzone.get(1)

也許是與“用戶類”的關系

static belongsTo = User
static hasMany = [friends:User,
                  streamposts:StreamPost]

通過更改StreamPost類來完成此操作:

class StreamPost {
    static belongsTo = [owner:User, audience:Friendzone]

    User owner
    Friendzone audience

    Date postTimestamp
    String postComment
    String postType

    static constraints = {
        postType inList: ['event','activitylevel','checkin','rating']
    }
}

與以下查詢:

def user = User.get(userID)
def posts = StreamPost.findAllByAudienceInList(user.friendzones.asList())

這個怎么樣?

def user = User.get(2)
def audiences = Friendzone.findAllByFriends(user)
def posts = StreamPost.findAllByAudienceInList(audiences)

我以這種方式編寫它,以使其更易於閱讀,並查找哪個查詢失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM