Grails many-to-many - find all objects that do not contain specific object

寵の児 提交于 2020-01-15 11:27:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!