Grails Gorm Query Restriction

129 views Asked by At

I have two domains

class ProductQuantity {
    Integer quantity

    static belongsTo = [productSize: ProductSize]
}

class ProductSize {

    String size

    static hasMany = [productQuantities : ProductQuantity]
}

I'm trying to build a query where I get all ProductQuantity by the productSize. I have the following query that works.

def productSize = ProductSize.findAllById(1);
def productQuantities = ProductQuantity.findAllByProductSize(productSize)

I'm looking to get the ProductQuanties in a single query rather than two separate queries.

2

There are 2 answers

2
Gaurav On BEST ANSWER
ProductQuantity.createCriteria().list {
    eq 'productSize', ProductSize.load(1)
}

or

ProductQuantity.withCriteria {
    eq 'productSize', ProductSize.load(1)
}

or

ProductQuantity.where {
    productSize == ProductSize.load(1)
}.list()

or

ProductQuantity.findAll("from ProductQuantity where productSize = ?", [ProductSize.load(1)])
0
MKB On

Yes, you can get this by createCriteria, like --

def productQuantities = ProductQuantity.createCriteria().list() {
    productSize {
        eq('id', 1)
    }
}