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?
and
is applied to criterias inside it, so there's no point applying it to a single statement. Top-level criterias areand
-ed by defauilt.- You usually better go without connector class, just by using
hasMany: Supermarket
andhasMany: Product
in domain classes. Connector table will be auto-generated by Hibernate. - If you stick with
ProductsSupermarket
connector class, do addbelongsTo: Supermarket
andbelongsTo: Product
to it class, and add 'hasMany: ProductsSupermarket' to other two, or you're losing Grails' GORM advantage. - There's a section "Querying Associations" in the doc.
- Object's
id
is as simple as that:mySupermarket.id
, ormySupermarket.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)
}
精彩评论