开发者

Grails createCriteria many-to-many

Imagine i have the following (this is a search mechanism for my website)

class Supermarket {    
String sp_n开发者_运维百科ame
String sp_street
}

class Products {
String p_name
String p_price
}

class products_supermarket{
Supermarket sp
Products pro
}

Now i want to create a criteria:

def c = Supermarket.createCriteria()
def results = c.list {
    like("sp_street", params.street)
    and {
        ************ ... params.product
    }
    maxResults(10)

}

Where i have the * i want to be able to find products whithin that supermaked searching on products_supermarket class. How to do that?

PS. If criteria works as an each() method, iterating over all supermarkets, i could use an if-else statment to search for products, and if found i could use: idEq(it), where it is the supermarket id. This way i would make it. My problem is, i dont know how to get current'sm supermarket id. Any help?


  1. and is applied to criterias inside it, so there's no point applying it to a single statement. Top-level criterias are and-ed by defauilt.
  2. You usually better go without connector class, just by using hasMany: Supermarket and hasMany: Product in domain classes. Connector table will be auto-generated by Hibernate.
  3. If you stick with ProductsSupermarket connector class, do add belongsTo: Supermarket and belongsTo: Product to it class, and add 'hasMany: ProductsSupermarket' to other two, or you're losing Grails' GORM advantage.
  4. There's a section "Querying Associations" in the doc.
  5. Object's id is as simple as that: mySupermarket.id, or mySupermarket.ident() if key field is named differently. id field is auto-added to class and table by default.

So the query is:

List<Supermarket> results = Supermarket.withCriteria {
    like("sp_street", params.street)
    productSupermarket {
        product {
            idEq(params.product)
        }
        // or just eq('product', someProduct)
    }
    ************ ... params.product
    maxResults(10)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜