![](/img/trans.png)
[英]Grails query with associations - find all in a table where id is not in another table
[英]Grails: “where” query with optional associations
我正在尝试运行“where”查询以查找与另一个域模型对象无关的域模型对象,或者如果是,则该域模型对象具有特定的属性值。 这是我的代码:
query = Model.where({
other == null || other.something == value
})
def list = query.list()
但是,结果列表仅包含与OR语句的第二部分匹配的对象。 它不包含与“other == null”部分匹配的结果。 我的猜测是,因为它正在检查关联对象中的值,所以它强制它仅检查实际具有此关联对象的条目。 如果是这种情况,我该如何创建此查询并实际使其正常工作?
您必须使用LEFT JOIN才能查找空关联。 默认情况下,Grails使用内部联接,不会为null结果加入。 使用withCriteria
如下所示,您应该得到预期的结果:
import org.hibernate.criterion.CriteriaSpecification
def results = Model.withCriteria {
other(CriteriaSpecification.LEFT_JOIN){
or{
isNull 'id'
eq 'something', value
}
}
}
UPDATE
我知道在DetachedCritieria中不能使用别名,其中人们会尝试在createCriteria/withCriteria
指定连接。 有关向DetachedCriteria添加功能的现有缺陷 。 只是为缺陷中提到的查询添加工作。
Model.where {
other {
id == null || something == value
}
}.withPopulatedQuery(null, null){ query ->
query.@criteria.subcriteriaList[0].joinType = CriteriaSpecification.LEFT_JOIN
query.list()
}
我宁愿使用withCriteria
而不是上面的hack 。
这可能有效:
query = Model.where({
isNull( other ) || other.something == value
})
如果这不起作用,请尝试以下方法:
other.id == null || other.something == value
更新:
或者使用good'ol标准查询:
list = Pack.withCriteria{
or{
isNull 'other'
other{ eq 'something', value }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.