我使用 Grails 2.2.4(Grails 2.3.11 中的相同行为)并且有一个引用域类 B 的域类 A
class A {
static hasOne = [b: B]
static constraints = { b nullable: true }
}
class B {
static belongsTo = [a: A]
}
我尝试找到所有具有 B 的 A 实例。
A.findAllByBIsNotNull()*.b
返回 B 和空值的列表:
[null, null, b1, b2, null, ...]
为何如此?
如果我使用,也会发生同样的情况
A.withCriteria {
isNotNull 'b'
}*.b
我做错了什么?
更新:
我意识到问题是因为
hasOne
.如果不是 static hasOne = [b: B]
,还有B b
, 有用。前者将外键移动到表 B,后者在表 A 中创建外键关系。那么为什么查询在前一种情况下不起作用,我如何查询所有
A
s,没有 B
当外键在 B 中时?
最佳答案
感谢@Koloritnij 的评论和@Alexander Suraphel 的修改答案,我终于解决了。
感谢那。
如果外键在 B
上表(由于 hasOne
),以下两个查询解决了这个问题:
查找所有 A
s 与 B
s: ( b
不是 null
):
A.withCriteria {
b {}
}
这会导致内部联接:
SELECT * FROM a INNER JOIN b ON a.id=b.a_id;
查找所有
A
s 没有 B
s ( b
是 null
): A.withCriteria {
createAlias('b', 'bAlias', CriteriaSpecification.LEFT_JOIN)
isNull 'bAlias.id'
}
这导致左外连接:
SELECT * FROM a LEFT OUTER JOIN b ON a.id=b.a_id WHERE b.id IS NULL;
关于对空 hasOne 关联的 Grails GORM 查询失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27110152/