views:

39

answers:

1

Hi,

I have a domain model that looks like this

Category 1 ------- * Type 1 ------- * Expense

Or in English "An expense has a type, and each type belongs to a category". I want to write a Criteria query that will find all expenses in a particular category. I tried both this

Expense.withCriteria {
    eq('type.category', someCategoryInstance)
}

and this

Expense.withCriteria {
    type {
        eq('category', someCategoryInstance)
    }    
}

But neither of them work, what am I missing?

Update

I've been asked to show the domain classes, so here they are:

public class Category {

    String description
    static hasMany = [types: Type]  
}

public class Type {

    String description
    static hasMany = [expenses: Expense]
    static belongsTo = [category: Category]
}

public class Expense {

    static belongsTo = [type: Type]

    Date date
    String description
    float amount
}
+1  A: 

Depending on how the associations are declared, the type table might not be joined in to the query. You can explicitly tell it to join with a join in your criteria.

Expense.withCriteria {
    join('type')
    type {
        eq('category', someCategoryInstance)
    }    
}
ataylor
This is probably why the default sort order in `static mapping` for an association doesn't work sometimes as well, I'm guessing (since it sometimes creates a join table for the association)?
Rob Hruska
The domain class associations looks ok to me. I wonder if there is a namespace collision between your Category class and groovy.lang.Category?
ataylor