我有以下域名模型:
class Product {
static hasMany = [ certificates : Certificate ]
}
class Certificate {
static hasMany = [ products : Product ]
static belongsTo = [ Product ]
}
如何找到所有不含特定证书的产品?最好带标准查询。
答案 0 :(得分:2)
使用Burt建议的方法here
您可以这样编写查询:
def p = new Product(message:"A")
p.addToCertificates (new Certificate(message:"1").save(flush:true) )
p.addToCertificates (new Certificate(message:"2").save(flush:true) )
p.addToCertificates (new Certificate(message:"3").save(flush:true) )
p.save(flush:true)
p = new Product(message:"B")
p.addToCertificates (new Certificate(message:"1").save(flush:true) )
p.addToCertificates (new Certificate(message:"2").save(flush:true) )
p.save(flush:true)
p = new Product(message:"C")
p.addToCertificates (new Certificate(message:"1").save(flush:true) )
p.addToCertificates (new Certificate(message:"2").save(flush:true) )
p.save(flush:true)
def cer= Certificate.findByMessage("3")
Product.executeQuery(
'select p from Product p where :certificate not in elements(p.certificates)',[certificate: cer])
输出:
结果:[B,C]
答案 1 :(得分:0)
试试这个:
Certificate certificate = Certificate.findTheSpecificOne()
def c = Product.createCriteria()
def results = c.list {
createAlias("certificates", "c", CriteriaSpecification.LEFT_JOIN)
not {'in'("c", certificate)}
}