开发者

createAlias() solution to return all associated rows does not work in all cases

开发者 https://www.devze.com 2023-02-24 16:55 出处:网络
Assuming the following domain objects: UserChallenge { String invitationKind } ChallengeGroup { UserChallenge challenge

Assuming the following domain objects:

UserChallenge {
  String invitationKind
}

ChallengeGroup {
  UserChallenge challenge
  UserGroup group
}

UserGroup {
  name
}

The following query returns challenges with a groups association which is partially filled with matching groups:

UserChallenge.withCriteria {
  eq('invitationKind', 'GRO开发者_开发知识库UP')
  groups {
    'in'('group.id', visibleGroupIds)
  }
}

In the post http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html it suggests using createAlias() and modifying the query above seems to work:

UserChallenge.withCriteria {
  eq('invitationKind', 'GROUP')
  createAlias('groups', 'g')
  'in'('g.group.id', visibleGroupIds)
}

However the following does not work:

UserChallenge.withCriteria {
  or {
    eq('invitationKind', 'OPEN')
    and {
      eq('invitationKind', 'GROUP')
      createAlias('groups', 'g')
      'in'('g.group.id', visibleGroupIds)
    }
  }
}

And returns only the challenges with matching visible group ids not the challenges which are 'OPEN'. It does not seem to matter where you put the createAlias() call.

The following does work:

UserChallenge.withCriteria {
  or {
    eq('invitationKind', 'OPEN')
    and {
      eq('invitationKind', 'GROUP')
      groups {
        'in'('group.id', visibleGroupIds)
      }
    }
  }
}

except that it returns the challenges with only groups which match (the original problem I am trying to solve).


Although the question is old,anyone getting same problem might find it useful. Using detached criteria query is yet another idea for achieving it. According to the information provided in the question I have tried to accomplish it using detached criteria query. Please find more about detached criteria here

def userGroup = new DetachedCriteria(UserGroup).build {
        eq("group.id", visibleGroupIds)
    }
    def getOb = UserChallenge.createCriteria()
    def listReturned = getOb.list {
        or{
            eq('invitationKind', 'OPEN')
            and {
                eq('invitationKind', 'GROUP')
                "groups" {
                    userGroup
                }
            }
        }
    }``
0

精彩评论

暂无评论...
验证码 换一张
取 消