Search code examples
grailsgrails-orm

Grails Gorm Query Restriction


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.


Solution

  • 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)])