我有一个像这样的域类:
class Person {
Team team
static hasMany = [history: PersonHistory]
}
class PersonHistory {
Team team
Person person
}
现在我想制定一个标准,将所有人排除在外。谁拥有一个不同团队的PersonHistory实例。
有些事情:
def c = Person.createCriteria()
def experiment = c.list {
history {
neProperty("team", history.team)
}
}
然而这是投掷(因为history.team):
Missing Property Exception
No such property: history for class: grails.orm.HibernateCriteriaBuilder
我可以在一个条件查询中执行此操作吗?如果是这样,怎么样?
答案 0 :(得分:1)
我还没有测试过,但我认为这应该可行:
Person.withCriteria {
createAlias 'history', 'h'
ne 'team', h.team
}
您必须为具有历史记录的联接创建别名。
修改强>
现在我明白了!使用以下示例数据:
def t1 = new Team(name: 'team 1').save()
def t2 = new Team(name: 'team 2').save()
def t3 = new Team(name: 'team 3').save()
def p1 = new Person(team: t1).save()
def p2 = new Person(team: t1).save()
def p3 = new Person(team: t2).save()
def p4 = new Person(team: t2).save()
def p5 = new Person(team: t3).save()
def ph1 = new PersonHistory(person: p1, team: t1).save()
def ph2 = new PersonHistory(person: p2, team: t3).save() // t3 instead of t1
def ph3 = new PersonHistory(person: p3, team: t2).save()
def ph4 = new PersonHistory(person: p4, team: t1).save() // t1 instead of t2
def ph5 = new PersonHistory(person: p5, team: t3).save(flush: true)
现在您可以执行以下条件:
List<Person> persons = PersonHistory.withCriteria {
createAlias 'person', 'p'
neProperty 'p.team', 'team'
projections {
property 'person'
}
}
这将返回正确的人p2
和p4