问题
I have following domain model:
class Product {
static hasMany = [ certificates : Certificate ]
}
class Certificate {
static hasMany = [ products : Product ]
static belongsTo = [ Product ]
}
How can I find all products that do not contain specific certificate? Preferably with criteria query.
回答1:
Using the approach that Burt suggested here
You can write your query like this:
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])
Output:
Result: [B, C]
回答2:
Try this:
Certificate certificate = Certificate.findTheSpecificOne()
def c = Product.createCriteria()
def results = c.list {
createAlias("certificates", "c", CriteriaSpecification.LEFT_JOIN)
not {'in'("c", certificate)}
}
来源:https://stackoverflow.com/questions/17074841/grails-many-to-many-find-all-objects-that-do-not-contain-specific-object